I am trying a certain program where I have to use Java Reflection API. Specifically, I need to know the actual data type of the fields in a given class. The way I found for doing this is to use the java.lang.reflect.Field class. This class exposes methods like getGenericType().getTypeName() and getType().getTypeName(). These return java.lang.String representation for the fully qualified names of the referenced data types in the class. For instance if my class is as follows:
class MyClass{Integer age;}
For the above scenario I would get that the data type of "age" is "java.lang.Integer type in String representation. However, the String representation would not be of much use in my case since I need the actual Integer data type not just an textual/String representation of its name. Is there any way to do so.
getType()method ofjava.lang.reflect.Fieldalready gives you the type, in the form of an instance ofClass. What else exactly do you think you need?.getTypeName()and be done with it?Class clazz = field.getDeclaringClass();Field.getType()would give me the Class representation of actual Data Type. But how to extract that actual data type from theClassrepresentation; I do not think that there is any method in Class API which gives access to the data type which it represents. Although, there are methods likegetSimpleName()andgetTypeName(), but again they return String representation of the actual Data Type. It would immensely help me if there be some method on whose return type I may utilizeinstanceofoperator, for instance.