check that one class inherits from another

1

I have a problem checking that one class inherits another.

I have the following code:

Class<Serializable> serializable = (Class<Serializable>) Class.forName("java.io.Serializable");
Class<String> stringClass = (Class<String>) Class.forName("java.lang.String");
System.out.println(stringClass.getClass().isAssignableFrom(serializable));
Serializable s = new String();
System.out.println("¿Porqueeeeeeeeee?");

As shown by line 4, string inherits from serializable, so I hope that isassignablefrom returns true.

I can not use instanceof because I get the classes by reflection, and therefore I have to check it from the object Class

    
asked by Daniel Garoz 19.12.2016 в 11:27
source

1 answer

0

To know if one class inherits from another simply use the keyword instanceof :

objetoAProbar instanceof Clase;

That returns true if objetoAProbar is an instance of that class or if it implements that interface, if it is an interface what you put on the right.

You can learn more about the subject in a answer that I published a while ago.

EDITO

If you can not use instanceof you can use it for your case:

Class<String> clazz = String.class;
System.out.println(Serializable.class.isAssignableFrom(clazz));

The output of this code will give you:

  

true

    
answered by 19.12.2016 / 11:35
source