[英]Java reflection - identify method return type
我有一个用例来确定方法的返回类型是否为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
条件。 有人可以帮助我理解这种行为吗?
您可以使用这样的类名进行检查
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.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.