我想检查泛型数组中是否存在特定异常的实例。 (我希望数组的所有元素都是一些异常(exception)。)
这是我尝试过的:
class Ideone
{
public static boolean isPresent(final Throwable t, final Class<?>[] exceptionArray){
for(Class<?> exc : exceptionArray){
if(t instanceof exc.getClass() ){
return true;
}
}
}
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
Class<?>[] my = {RuntimeException.class};
isPresent(RuntimeException.class, my);
}
}
这是一个 IDEOne link如果这可以帮助您模拟。
在这里,我收到错误 expected )
在 IntelliJ Idea 上,悬停时,我收到错误 cannot resolve symbol 'getClass'
。
有什么想法吗?
谢谢。
最佳答案
如果你想检查实例,试试这个代码:
class Ideone {
public static boolean isPresent(final Throwable t, final Class<?>[] exceptionArray) {
for (Class<?> exc : exceptionArray) {
if (exc.isAssignableFrom(t.getClass())) {
return true;
}
}
return false;
}
public static void main(String[] args) throws java.lang.Exception {
// your code goes here
Class<?>[] my = { RuntimeException.class };
System.out.println("RuntimeException: " + isPresent(new RuntimeException(), my));
System.out.println("IllegalStateException: " + isPresent(new IllegalStateException(), my));
System.out.println("NoSuchMethodException: " + isPresent(new NoSuchMethodException(), my));
}
}
结果:
RuntimeException: true
IllegalStateException: true
NoSuchMethodException: false
或者如果你想检查异常类是否匹配,则使用此代码:
class Ideone {
public static boolean isPresent(final Throwable t, final Class<?>[] exceptionArray) {
for (Class<?> exc : exceptionArray) {
if (exc.equals(t.getClass())) {
return true;
}
}
return false;
}
public static void main(String[] args) throws java.lang.Exception {
// your code goes here
Class<?>[] my = { RuntimeException.class };
System.out.println("RuntimeException: " + isPresent(new RuntimeException(), my));
System.out.println("IllegalStateException: " + isPresent(new IllegalStateException(), my));
System.out.println("NoSuchMethodException: " + isPresent(new NoSuchMethodException(), my));
}
}
结果:
RuntimeException: true
IllegalStateException: false
NoSuchMethodException: false
第一个错误是传递 RuntimeException.class
而不是实例 new RuntimeException()
。
其次,exc
已经是一个类对象,您不需要 exc.getClass()
。
第三,如果没有发现异常,您不会返回 false。
关于java - 检查泛型数组中是否存在异常实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36542835/