首页 > 解决方案 > 如何检查类型化类的类型

问题描述

我在已声明为接受参数的方法中传递参数type class<?>...其他,在传递参数之后String.classInteger.class我想知道已在此方法中传递的类型(类)参数。

我收到什么参数,我将它转换为对象并试图检查类型,但它不起作用。

public void processVarargIntegers(String label, Class<?>... others) {

    System.out.println(String.format("processing %s arguments for %s", others.length, label));
    Arrays.asList(others).forEach(a -> {

        try {
            Object o = a;
            if (o instanceof Integer) {
                System.out.println(" >>>>>>>>>>>>> Integer");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    });
}
public void processVarargIntegers(String label, Class<?>... others) {

    System.out.println(String.format("processing %s arguments for %s", others.length, label));
    Arrays.asList(others).forEach(a -> {

        try {
            Object o = a;
            if (o instanceof Integer) {
                System.out.println(" Integer");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    });
}

如果 a 是整数的实例,则System.out.println(" Integer");应该执行

标签: javareflection

解决方案


该 if 语句永远不会起作用,因为您的对象是Class<?>. 这将起作用:

if (o == Integer.class)
    System.out.println("Integer")

推荐阅读