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

发布于 2024-08-14 03:44:28 字数 718 浏览 10 评论 0原文

我面临一个用例,我想声明一个带有初始化语句的静态最终字段,该语句被声明为抛出已检查的异常。通常情况下,它看起来像这样:

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

我这里遇到的问题是 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);
    }
}

因为静态块真的非常难以阅读。有谁对如何以良好、干净的方式处理此案有建议吗?

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

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

过气美图社 2024-08-21 03:44:28

如果您不喜欢静态块(有些人不喜欢),那么另一种选择是使用静态方法。 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);
    }  
}

或者:(

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

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

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

安穩 2024-08-21 03:44:28

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

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.

心清如水 2024-08-21 03:44:28

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

static blocks aren't difficult to read. 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. But again, I'd go for the static option.

神也荒唐 2024-08-21 03:44:28

您可以使用用 Lombok 的 @SneakyThrows 注解的方法。

public static final ObjectName OBJECT_NAME = createObjectName();

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

此注解使已检查的异常表现得像未检查的异常。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文