简体   繁体   中英

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

The reason for this is probably because the build() method does not declare it may throw the checked Exception that the constructor might throw.

Is there a way to let Lombok declare this without explicitly implementing the build() method ourselves?

@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.

Move the @Builder annotation to the constructor and it will work:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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