Reputation: 4737
I'm having a little trouble putting this simple example together.
With reflection, I can get a type of a certain declared field. But how do I compare this to a known class?
What I'm trying to do is something like:
Type t = myField.getType();
if (t.equals(MyOwnClass.class)) {
// Now I know myField is of type MyOwnClass
}
Upvotes: 4
Views: 2255
Reputation:
Essentially, you already found the correct answer, with only a bit of commenting needed. The other answer is just wrong.
Firstly, getType()
returns a Class<?>
reference, with a Class
class implementing a Type
interface; using a Type
variable for a isAssignableFrom()
call is wrong for two reasons:
Type
doesn't have isAssignableFrom()
methodClass#isAssignableFrom()
requires a Class<?>
parameter, not a Type
parameterSimply put, you probably shouldn't compare a Class
/Type
this way, because you're hiding the relevant typing and requiring unnecessary casts. On the other hand, you just upcasted the Class<?>
reference to Type
reference, and since equals()
called on Class
(even casted to Type
) actually calls Object#equals()
, it simply calls
public boolean equals(Object obj) {
return (this == obj);
}
straight from Object.java
, as Class.java
doesn't override it in any way.
Secondly, you could do what you already done, but is one of the proper ways:
if ( myField.getType() == MyOwnClass.class ) {
// Now I know myField is of type MyOwnClass
} // note that this requires a single ClassLoader to be used! Two ClassLoaders could in theory load one class with two separate Class instances
alternatively, you could
if ( myField.getType().getCanonicalName().equals( MyOwnClass.class.getCanonicalName() ) {
// Now I know myField is of type MyOwnClass
} // note that this uses a name comparison, not a class comparison
or even
if ( myField.getType().isAssignableFrom( MyOwnClass.class )) {
// Now I know MyOwnClass objects can be cast to myField.getType() safely
} // note: they are either equal or MyOwnClass is a subclass of myField.getType()
tl;dr Using equals()
on a Class
object is unnecessary here, as two equal classes have to be ==
anyway, as is casting to Type
- still, the answer you provided in your question is a working solution indeed.
Upvotes: 1
Reputation: 3161
You could use the function
isAssignableFrom()
to determine this. Note, that also inherited classes are allowed.
Type t = myField.getType();
if (t.isAssignableFrom(MyOwnClass.class)) {
// Now I know myField is of type MyOwnClass
}
Upvotes: 0