Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check if a type is a subclass of another type?

Tags:

java

I need to check if an instance of the reflection Field type, as retrieved by Field.getType() is an instance of another class that extends a specific class, GenericModel.

I'm trying something as in the following pseudo code snippet:

if(field.getType() "is_a_superclass_of" GenericModel) {
    ... then do something with it
}

How do I do this?

When I try something like:

field.getType().isAssignableFrom(Language.class)

I get a result, true, which means it is of the Language class, which extends GenericModel. However;

field.getType().isAssignableFrom(GenericModel.class)

returns false?

field.getType() == "za.co.company.package.model.Language"
like image 327
josef.van.niekerk Avatar asked Jul 26 '11 21:07

josef.van.niekerk


2 Answers

Try

GenericModel.class.isAssignableFrom(field.getType())
like image 39
jontro Avatar answered Oct 20 '22 01:10

jontro


You have the test backwards.

GenericModel.class.isAssignableFrom(field.getType())
like image 74
Jim Garrison Avatar answered Oct 19 '22 23:10

Jim Garrison