Lombok Builder 可以处理可能抛出异常的构造函数吗?
Can a Lombok Builder handle a constructor that may throw an Exception?
以下不编译
@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
}
}
因为java: unreported exception javax.xml.bind.JAXBException in default constructor
原因可能是因为build()
方法没有声明它可能会抛出构造函数可能抛出的checkedException
有没有办法让 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);
}
}
}
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
注释移动到构造函数,它将起作用:
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");
}
}
来自文档
以下不编译
@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
}
}
因为java: unreported exception javax.xml.bind.JAXBException in default constructor
原因可能是因为build()
方法没有声明它可能会抛出构造函数可能抛出的checkedException
有没有办法让 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);
}
}
}
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
注释移动到构造函数,它将起作用:
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");
}
}
来自文档