In Java, Class has an isAssignableFrom method defined as follows:
public boolean isAssignableFrom(Class<?> cls)Determines if the class or interface represented by this
Classobject is either the same as, or is a superclass or superinterface of, the class or interface represented by the specifiedClassparameter. It returnstrueif so; otherwise it returnsfalse. If thisClassobject represents a primitive type, this method returnstrueif the specifiedClassparameter is exactly thisClassobject; otherwise it returnsfalse.Specifically, this method tests whether the type represented by the specified
Classparameter can be converted to the type represented by thisClassobject via an identity conversion or via a widening reference conversion. See The Java Language Specification, sections 5.1.1 and 5.1.4 , for details.Parameters:
cls- theClassobject to be checkedReturns:
the
booleanvalue indicating whether objects of the typeclscan be assigned to objects of this class
Class implements the Type interface. Is there an equivalent isAssignableFrom method that works on Types instead of just Classes? For example, is there a method that determines if a variable of type List<String> (which would be represented via an instance of ParameterizedType) can be assigned to a variable of type List<? extends Object>?
Have a look at javaRuntype -- I've found it useful. It can produce representations of types from instances of java.lang.reflect.Type, and test assignability between them.
Guava's TypeToken utility provides that functionality. Your query could be answered like this:
// represents List<String>
ParameterizedType stringList = ...;
// represents List<? extends Object>
TypeToken objectList = new TypeToken<List<? extends Object>>(){};
boolean isAssignable = objectList.isAssignableFrom( stringList );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With