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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1866770/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 18:18:39  来源:igfitidea点击:

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

javaexceptionstaticfinalinitializer

提问by Romain

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, it'd look like this:

我面临一个用例,我想static final用声明为抛出已检查异常的初始化语句声明一个字段。通常,它看起来像这样:

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

The issue I have here is that the ObjectNameconstructor 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). The java compiler won't let me just ignore this (as it's a checked exception), and I would prefer not to resort to:

我在这里遇到的问题是ObjectName构造函数可能会抛出各种已检查的异常,我不在乎(因为我知道我的名字是有效的,如果它不幸崩溃也没关系,以防万一)。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?

因为静态块真的非常难以阅读。有没有人对如何以一种漂亮、干净的方式处理这种情况提出建议?

回答by Tom Hawtin - tackline

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

回答by BalusC

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. E.g. 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.

您的代码完全有效。我觉得读起来不难。其他方式只会让情况变得更糟。它们只是初学者难以阅读,因为他们中的大多数人都不熟悉。只需遵循有关代码中元素排序的标准约定。例如,不要将静态初始化器放在代码的中间或整个底部,也不要将它们中的多个散布在整个类中。只需在静态声明之后将一个放在顶部。

回答by Bozho

staticblocks aren't difficult to read. So I'd recommend that solution. However, you can wrap your object in another object, for example ObjectNameWrapperwhich shares an interfacewith your ObjectName, and whose constructor calls your ObjectNameconstructor, hiding all checked exceptions that occur. But again, I'd go for the static option.

static块不难阅读。所以我推荐这个解决方案。但是,您可以将您的对象包装在另一个对象中,例如 ObjectNameWrapper,它interface与您的共享ObjectName,并且其构造函数调用您的ObjectName构造函数,隐藏发生的所有已检查异常。但同样,我会选择静态选项。