Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I compare classes using reflection?

I am trying to determine the class type of a class using reflection and then do something specific. For example, if the class is a double, use a double specific method.

I am attempting to use


  if(f.getClass() == Double.class)

However, I am getting a compiler error:

"Incompatible operand types Class <capture#1-of ? extends Field> and Class<Double>"

What is the proper way to do this?

Edit: to be more clear

f is of type Field. obtained by reflection in a loop


  (Field f : instance.getDeclaredFields())
like image 335
kgrad Avatar asked Feb 03 '23 11:02

kgrad


2 Answers

Interesting error message (I didn't know '==' operator would check those). But based on it, I suspect that your comparison is wrong: you are trying to see if Field class (theoretically its super-class, but only in theory -- Field is final) is same as Double.class, which it can not be.

So: yes, comparison should work, iff you give it right arguments. So I suspect you want to do:

if (f.getType() == Double.class)

instead. And that should work, given that Double is a final class. Otherwise "isAssignableFrom" would be more appropriate.

like image 129
StaxMan Avatar answered Feb 06 '23 12:02

StaxMan


If you have objects then use

if (f instanceof Double) { }

Another interesting thing is method isAssignableFrom:

if (f.getClass().isAssignableFrom (Double.class)) { }

But in general it's a bad style. Use polymorphism to implement logic which depends on class types.


Answer for comment: f instanceof Double works fine.

You probably wrote something like this:

float f = 1.1f;
if (f instanceof Double) { ..}

And smart java compiler says that you've got CE. BUT:

public static boolean isInstanceOfDouble (Object obj) {
   return obj instanceof Double;
}

psvm (String [] args) {
   sout (isInstanceOfDouble (1.1f);
}

..this works fine

like image 27
Roman Avatar answered Feb 06 '23 11:02

Roman