java - 检查泛型数组中是否存在异常实例

标签 java arrays

我想检查泛型数组中是否存在特定异常的实例。 (我希望数组的所有元素都是一些异常(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/

相关文章:

java - NotificationListenerService sendBroadcast 不起作用?

java - Selenium、Firefox 和 GeckoDriver

C:指向数组的指针和字符数组

c - C 中数组声明和定义的时间复杂度是多少?

javascript - 删除javascript数组中的数据列

arrays - 如何检查数组中的所有元素是否出现不超过两次?

java - 泛型类的新对象上的绑定(bind)不匹配

java - Eclipse:JRE 系统库选择 - 执行环境与备用 JRE

java - 在 Intellij for Java 的单独一行上包装链式方法调用

c# - 如何将我的列表显示到 C# 数据网格中?