gpt4 book ai didi

java - 有什么方法可以不将 'instance of' 用于我无法扩展的对象?

转载 作者:行者123 更新时间:2023-11-30 06:13:47 25 4
gpt4 key购买 nike

我有一个自定义异常,其中有几个继承自异常类的属性。

根据异常的实例,我想返回一个代码。代码:

public int manageException(Exception exception) {               
int code = 0;

if (exception instanceof MyCustomException) {
code = ((MyCustomException) exception).getCode();
} else if (exception instanceof NestedRuntimeException) {
code = 444;
} else if (exception instanceof HibernateException) {
code = 555;
} else {
code = 666;
}

return code;
}

最佳答案

如果

  • 您需要在多个位置处理这些异常,并且

  • 您不希望在每个位置有多个 catch block (每个异常类型一个)

...那么 instanceof 就和您在 Java 7 中可能获得的一样干净。

尽管如此,您可以这样做:

public void manageException(Runnable r) {
try {
r.run();
}
catch (NestedRuntimeException nre) {
throw new MyCustomException(444, nre);
}
catch (HibernateException he) {
throw new MyCustomException(555, he);
}
catch (Exception e) {
throw new MyCustomException(666, e);
}
}

...然后在任何需要它的地方:

try {
this.manageException(new Runnable() {
@Override
public void run() {
// Do something
}
});
}
catch (MyCustomException mce) {
int code = mce.getCode();
}

...但这并没有给你带来太多好处,而且它真的很丑。 :-)

在 Java 8 中,它更加简洁。 manageException 是相同的,但调用只是:

try {
this.manageException(() => {
// Do something here
});
}
catch (MyCustomException mce) {
int code = mce.getCode();
}

对我来说,Java 8 版本几乎开始胜过 instanceof。 Java 7 版本,没那么多。

(为什么 Runnable 在上面?因为 JDK 作者决定不定义一个新的标准 functional interface 不接受任何参数并且没有返回值; more in this question 。他们概括了Runnable 代替。如果语义打扰你(他们会打扰我),你可以定义你自己的。)

关于java - 有什么方法可以不将 'instance of' 用于我无法扩展的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31431086/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com