How to handle a static final field initializer that throws checked exception

后端 未结 4 1101
迷失自我
迷失自我 2020-12-02 17:01

I am facing a use case where I would like to declare a static finalfield with an initializer statement that is declared to throw a checked exception. Typically,

4条回答
  •  悲哀的现实
    2020-12-02 17:28

    You can use a method annotated with Lombok's @SneakyThrows

    public static final ObjectName OBJECT_NAME = createObjectName();
    
    @SneakyThrows(SomeException.class)
    private static ObjectName createObjectName() {
        return new ObjectName("foo:type=bar");
    }
    

    This annotation makes a checked exception behaves like an unchecked one.

提交回复
热议问题