简体   繁体   English

如何处理引发检查异常的静态最终字段初始值设定项

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

I am facing a use case where I would like to declare a static final field with an initializer statement that is declared to throw a checked exception.我正面临一个用例,我想用声明为抛出已检查异常的初始化语句声明一个static final字段。 Typically, it'd look like this:通常,它看起来像这样:

public static final ObjectName OBJECT_NAME = new ObjectName("foo:type=bar");

The issue I have here is that the ObjectName constructor may throw various checked exceptions, which I don't care about (because I'd know my name is valid, and it's allright if it miserably crashes in case it's not).我在这里遇到的问题是ObjectName构造函数可能会抛出各种已检查的异常,我并不关心(因为我知道我的名字是有效的,如果它不幸崩溃也没关系,以防万一)。 The java compiler won't let me just ignore this (as it's a checked exception), and I would prefer not to resort to: java编译器不会让我忽略这个(因为它是一个检查异常),我不想诉诸于:

public static final ObjectName OBJECT_NAME;
static {
    try {
        OBJECT_NAME = new ObjectName("foo:type=bar");
    } catch (final Exception ex) {
        throw new RuntimeException("Failed to create ObjectName instance in static block.", ex);
    }
}

Because static blocks are really, really difficult to read.因为静态块真的非常难以阅读。 Does anyone have a suggestion on how to handle this case in a nice, clean way?有没有人对如何以一种漂亮、干净的方式处理这种情况提出建议?

If you don't like static blocks (some people don't) then an alternative is to use a static method.如果您不喜欢静态块(有些人不喜欢),那么另一种方法是使用静态方法。 IIRC, Josh Bloch recommended this (apparently not in Effective Java on quick inspection). IIRC,Josh Bloch 推荐了这个(显然不是在快速检查的 Effective Java 中)。

public static final ObjectName OBJECT_NAME = createObjectName("foo:type=bar");

private static ObjectName createObjectName(final String name) {
    try {
        return new ObjectName(name);
    } catch (final SomeException exc) {
        throw new Error(exc);
    }  
}

Or:或者:

public static final ObjectName OBJECT_NAME = createObjectName();

private static ObjectName createObjectName() {
    try {
        return new ObjectName("foo:type=bar");
    } catch (final SomeException exc) {
        throw new Error(exc);
    }  
}

(Edited: Corrected second example to return from method instead of assign the static .) (编辑:更正第二个示例以从方法返回而不是分配static 。)

Your code is perfectly valid.您的代码完全有效。 I don't find it difficult to read.我觉得读起来不难。 Other ways would only make it more worse.其他方式只会让情况变得更糟。 They're only difficult to read for starters, because most of them are not familiar with that.它们只是初学者难以阅读,因为他们中的大多数人都不熟悉。 Just follow the standard conventions with regard to ordering of the elements in the code.只需遵循有关代码中元素排序的标准约定。 Eg do not put static initializers halfway or at the whole bottom of the code and also do not have multiple of them spreading over the class.例如,不要将静态初始化器放在代码的中间或整个底部,也不要将它们中的多个散布在整个类中。 Just put one at top, after static declarations.只需在静态声明之后将一个放在顶部。

static blocks aren't difficult to read. static块不难阅读。 So I'd recommend that solution.所以我推荐这个解决方案。 However, you can wrap your object in another object, for example ObjectNameWrapper which shares an interface with your ObjectName , and whose constructor calls your ObjectName constructor, hiding all checked exceptions that occur.但是,您可以将您的对象包装在另一个对象中,例如ObjectNameWrapper ,它与您的ObjectName共享一个interface ,并且其构造函数调用您的ObjectName构造函数,隐藏发生的所有已检查异常。 But again, I'd go for the static option.但同样,我会选择静态选项。

You can use a method annotated with Lombok's @SneakyThrows您可以使用用 Lombok 的@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.此注释使受检查的异常表现得像未经检查的异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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