nawazish-stackoverflow
nawazish-stackoverflow

Reputation: 283

Java Reflection API: How to know the type of field in a Java class

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.

Upvotes: 4

Views: 8580

Answers (1)

voji
voji

Reputation: 493

You can use the class returned by Field getType method. See the example code bellow:

import java.lang.reflect.Field;

    public class Main {

      public static void main(String[] args) {
        Field[] declaredFields = MyClass.class.getDeclaredFields();
        for (Field declaredField : declaredFields) {
          Class<?> fieldType = declaredField.getType();
          String result=fieldType.getName();
          System.out.println(result);
        }
      }

    }

But be careful with primitive data types (example: boolean). In this case the fieldType.getName() function returns a uninstantiated string (boolean). You can handle it differently. The list of internal data types is here.

Upvotes: 2

Related Questions