gpt4 book ai didi

java - 在不使用 instanceof 的情况下获取异常是否为 instanceof 的复杂方法

转载 作者:行者123 更新时间:2023-12-04 15:41:02 27 4
gpt4 key购买 nike

我正在编写一个方法,如果异常是 *someClass* 的实例,它将返回 true。但是我无法导入其中一个类,因为它在另一个模块中。我无法将该模块添加到项目中,所以我想,我不能使用 instanceof。

我考虑创建一个 StringsMap - 异常的类名并检查我的异常的类名是否在映射中,但我认为它会相当缓慢和丑陋。

方法如下:

public boolean checkExceptionClass(Throwable cause){
return (cause instanceof firstException
|| cause instanceof secondException
|| cause instanceof iDontHaveThatClassException // can't do that
|| cause instanceof fourthException);
}

也许我眼皮底下没有找到解决该问题的好方法。非常感谢任何想法和建议。

最佳答案

您可以尝试使用 .getClass() 和 getSimpleName(),例如:

Integer integer = Integer.valueOf(1);

if(integer.getClass().getSimpleName().equals("Integer") {
return true
}

所以基本上你可以使用你不能导入的类的名称,值得一提的是硬编码不是最佳实践

关于java - 在不使用 instanceof 的情况下获取异常是否为 instanceof 的复杂方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57788691/

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