【问题标题】:Java reflection - identify method return typeJava 反射 - 识别方法返回类型
【发布时间】:2021-11-07 11:08:00
【问题描述】:

我有一个用例来确定方法的返回类型是否为List 类型。为了检查返回类型,我使用了Class#isAssignable 方法并遇到了这种行为。

public class ObjectReturnType {
    public static void main(String[] args) throws NoSuchMethodException {
        Method method1 = ObjectReturnType.class.getDeclaredMethod("objectReturnType");
        Class<? extends Object> returnType1 = method1.getReturnType();
        if (returnType1.isAssignableFrom(List.class)) {
            System.out.println("Yes it is.");
        }

        Method declaredMethod2 = ObjectReturnType.class.getDeclaredMethod("listReturnType");
        Class<? extends Object> returnType2 = declaredMethod2.getReturnType();
        if (returnType2.isAssignableFrom(List.class)) {
            System.out.println("Yes it is.");
        }

    }

    public Object objectReturnType() {
        return null;
    }

    public List<String> listReturnType() {
        return List.of("");
    }
}

这两种方法都通过if 条件,我期望只有listReturnType 方法通过if 条件,不知道为什么objectReturnType 方法会通过if 条件。有人可以帮我理解这种行为吗?

【问题讨论】:

  • List 可分配 Object,因此Object 可分配来自 List。这里没有错。你的意思是颠倒这两种类型吗? if (List.class.isAssignableFrom(returnType1))
  • 试试Class&lt;?&gt; object = Object.class, list = List.class; System.out.println(object.isAssignableFrom(list)); System.out.println(list.isAssignableFrom(object));

标签: java reflection


【解决方案1】:

您可以使用这样的类名进行检查

public class ObjectReturnType {

    public static void main(String[] args) throws NoSuchMethodException {
        Method method1 = ObjectReturnType.class.getDeclaredMethod("objectReturnType");
        Class<?> returnType1 = method1.getReturnType();
        if (List.class.getName().equals(returnType1.getName())) {
            System.out.println("Yes it is.");
        } else {
            System.out.println("Yes it not List.");
        }

        Method declaredMethod2 = ObjectReturnType.class.getDeclaredMethod("listReturnType");
        Class<?> returnType2 = declaredMethod2.getReturnType();
        if (List.class.getName().equals(returnType2.getName())) {
            System.out.println("Yes it is.");
        } else {
            System.out.println("Yes it not List.");
        }
    }

    public Object objectReturnType() {
        return null;
    }

    public List<String> listReturnType() {
        return List.of("");
    }

}

输出将是

No it not List.
Yes it is.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多