如何处理引发检查异常的静态最终字段初始值设定项 [英] How to handle a static final field initializer that throws checked exception

查看:30
本文介绍了如何处理引发检查异常的静态最终字段初始值设定项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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:

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

我在这里遇到的问题是 ObjectName 构造函数可能会抛出各种检查异常,我不关心(因为我知道我的名字是有效的,如果它很糟糕也没关系否则会崩溃).java 编译器不会让我忽略这个(因为它是一个已检查的异常),我不想诉诸于:

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

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?

推荐答案

如果您不喜欢静态块(有些人不喜欢),那么另一种选择是使用静态方法.IIRC,Josh Bloch 推荐了这个(显然不在 Effective Java 中快速检查).

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

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);
    }  
}

或者:

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);
    }  
}

(更正第二个示例以从方法返回而不是分配 static.)

(Edited: Corrected second example to return from method instead of assign the static.)

这篇关于如何处理引发检查异常的静态最终字段初始值设定项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆