简体   繁体   English

Lombok Builder可以处理可能抛出异常的构造函数吗?

[英]Can a Lombok Builder handle a constructor that may throw an Exception?

The following does not compile 以下内容无法编译

@Builder
public class ExampleClass {
    private final String field1;
    private final int field2;

    private ExampleClass (String field1, int field2) throws JAXBException {
        // all args constructor that might throw an exception
    }
}

because of java: unreported exception javax.xml.bind.JAXBException in default constructor 因为java: unreported exception javax.xml.bind.JAXBException in default constructorjava: unreported exception javax.xml.bind.JAXBException in default constructor

The reason for this is probably because the build() method does not declare it may throw the checked Exception that the constructor might throw. 原因可能是因为build()方法没有声明它可能抛出构造函数可能抛出的已检查Exception。

Is there a way to let Lombok declare this without explicitly implementing the build() method ourselves? 有没有办法让Lombok在没有显式实现build()方法的情况下声明这一点?

@Builder
public class ExampleClass {
    private final String field1;
    private final int field2;

    private ExampleClass(String field1, int field2) throws JAXBException {
        // all args constructor that might throw an exception
    }

    /**
     * I don't want to explicitly declare this
     */
    public static class ExampleClass Builder {
        public ExampleClass build() throws JAXBException {
            return new ExampleClass(field1, field2);
        }
    }
}

From the documentation : 文档

This only works if you haven't written any explicit constructors yourself. 这仅适用于您自己没有编写任何显式构造函数的情况。 If you do have an explicit constructor, put the @Builder annotation on the constructor instead of on the class. 如果您确实有一个显式构造函数,请将@Builder注释放在构造函数上而不是类上。

Move the @Builder annotation to the constructor and it will work: @Builder注释移动到构造函数,它将起作用:

public class Foo {
    private final String field1;
    private final int field2;

    @Builder
    private Foo(String field1, int field2) throws JAXBException
    {
        this.field1 = field1;
        this.field2 = field2;
        throw new JAXBException("a");
    }
}

From the documentation 从文档中

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM