I am having a use case to identify the return type of a method is of List
type or not. To check the return type, I am using Class#isAssignable
method and came across this behavior.
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("");
}
}
Both methods are going through the if
condition, I was expecting only the listReturnType
method to go through the if
condition, not sure why the objectReturnType
method is going the if
condition. Can someone help me to understand this behavior?
Aucun commentaire:
Enregistrer un commentaire