Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I compare types in Java with reflection

I have following code and now I have type, but I need to have some kind of switch to know if type is for example of String and then do handling for strings. So how can I check if Type t is type of String?

Type t = bean.getClass().getDeclaredField(fieldName).getType();
like image 296
newbie Avatar asked Jun 25 '10 19:06

newbie


1 Answers

Do you want to do a name check or an object-based check?

Since Class implements Type, you can actually go directly and do the equals against String.class For instance: if (t.equals(String.class))

If, however, you want to do a check based on name, then first check if t is an instance of Class, and then cast it to Class, obtain the full type name, and compare.

like image 200
Uri Avatar answered Nov 08 '22 08:11

Uri