Comparing Java Type to Class

I'm having trouble getting this simple example together.

With reflection, I can get the type of a specific declared field. But how do I compare this to a famous 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
}
+4
source share
2 answers

You can use the function

isAssignableFrom() 

to determine this. Note: inherited classes are also valid.

Type t = myField.getType();
if (t.isAssignableFrom(MyOwnClass.class)) {
    // Now I know myField is of type MyOwnClass
}
0
source

In fact, you have already found the correct answer, with a few comments needed. The other answer is simply incorrect.

-, getType() Class<?>, Class Type; Type isAssignableFrom() :

  • Type isAssignableFrom()
  • Class#isAssignableFrom() Class<?>, Type

, , , Class/Type , . , Class<?> Type, , equals() Class ( Type), Object#equals(),

public boolean equals(Object obj) {
    return (this == obj);
}

Object.java, Class.java .

-, , , :

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

,

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

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 equals() Class , ==, Type - , , : .

0

Source: https://habr.com/ru/post/1528949/


All Articles