[英]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
的java: unreported exception javax.xml.bind.JAXBException in default constructor
原因可能是因為build()
方法沒有聲明它可能拋出構造函數可能拋出的已檢查Exception。
有沒有辦法讓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);
}
}
}
從文檔 :
這僅適用於您自己沒有編寫任何顯式構造函數的情況。 如果您確實有一個顯式構造函數,請將@Builder注釋放在構造函數上而不是類上。
將@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");
}
}
從文檔中
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.