josef.van.niekerk
josef.van.niekerk

Reputation: 12121

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

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"

Upvotes: 5

Views: 571

Answers (3)

André Puel
André Puel

Reputation: 9219

You may want to invert the order of your verification:

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

In this code, you ask if GenericModel is a super class of "field.getType()"

Upvotes: 1

jontro
jontro

Reputation: 10636

Try

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

Upvotes: 3

Jim Garrison
Jim Garrison

Reputation: 86774

You have the test backwards.

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

Upvotes: 7

Related Questions