Is there an alternative to Class.isAssignableFrom that works with type objects?

In Java, the Class has the isAssignableFrom method defined as follows:

 public boolean isAssignableFrom(Class<?> cls) 

Determines whether the class or interface represented by this Class object is either the same or the superclass or superinterface of the class or interface represented by the specified Class parameter. It returns true if so; otherwise, it returns false . If this Class object represents a primitive type, this method returns true if this Class object is the specified Class parameter; otherwise, it returns false .

In particular, this method checks whether the type represented by the specified Class parameter can be converted to the type represented by this Class object, by means of identifier conversion or by using an expanding reference transformation. See the Java Language Specification, sections 5.1.1 and 5.1.4 for details.

Options:

cls - Class object to be checked

Return:

a boolean value indicating whether objects of type cls can be assigned to objects of this class

Class implements the Type interface. Is there an equivalent isAssignableFrom method that works on Type instead of Class es? For example, is there a method that determines whether a variable of type List<String> (which will be represented through an instance of ParameterizedType ) can be assigned to a variable of type List<? extends Object> List<? extends Object> ?

+7
source share
3 answers

Take a look at javaRuntype - I found this useful. It can create type representations from java.lang.reflect.Type instances and assign tests between them.

+2
source

The Guava utility TypeToken provides this functionality. Your request could be answered as follows:

 // represents List<String> ParameterizedType stringList = ...; // represents List<? extends Object> TypeToken objectList = new TypeToken<List<? extends Object>>(){}; boolean isAssignable = objectList.isAssignableFrom( stringList ); 
+1
source

You can use between any List <...> - s, protection is weaker than usual.

try it

  List<String> a = new Vector<String>(); List<Integer> b = new Vector<Integer>(); Integer i = new Integer(0); b.add(2); a = (List<String>) (Object) b; System.out.println((Object)a.get(0)); 

there will be no exceptions.

This is because generics is only compilation time.

If you write

  System.out.println(a.get(0)); 

you will get a ClassCastException because the version of the println version defined at compile time will be println (String arg).

And so the answer to the question: it is wrong to have such an alternative.

0
source

All Articles