繁体   English   中英

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 constructorjava: 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.

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