Reputation: 198
How can I check if Class<Object>
stores class that can be casted to another class, e.g. String
? I tried to use clazz.isInstance(String.class)
, but this check always return true, because e.g. String is instance of Object.
Note that I cant use instanceof
.
Upvotes: 0
Views: 595
Reputation: 2461
You're looking for isAssignableFrom
A String is an Object but an Object is not necessarily a String. So Object is assignable from String, but not the other way around.
class Scratch {
public static void main(String[] args) {
System.out.println(Object.class.isAssignableFrom(String.class)); //true
System.out.println(String.class.isAssignableFrom(Object.class)); //false
}
}
Upvotes: 2