W3docs

Reflection generic get field value

To get the value of a generic field using reflection in Java, you can use the get() method of the Field class, which returns the value of the field as an Object.

To get the value of a generic field using reflection in Java, you can use the get() method of the Field class, which returns the value of the field as an Object. You can then cast the returned value to the appropriate type.

Here is an example of how to do this:


import java.lang.reflect.Field;

class MyClass<T> {
    public T field;
}

// ...

MyClass<String> myObject = new MyClass<>();
myObject.field = "value";

try {
    Field field = MyClass.class.getDeclaredField("field");
    Object fieldValue = field.get(myObject);
    if (fieldValue instanceof String) {
        String stringValue = (String) fieldValue;
        // do something with the string value
    }
} catch (NoSuchFieldException | IllegalAccessException e) {
    e.printStackTrace();
}

This code gets the value of the field field of the myObject object and casts it to a String.

If you know the type of the field, you can use the getType() method of the Field class to get the Class object for the field type. However, due to Java's type erasure, getType() returns Object.class for generic fields, so checking against String.class will always be false. Instead, use the instanceof operator to safely verify and cast the value at runtime.

Here is an example:


import java.lang.reflect.Field;

Field field = MyClass.class.getDeclaredField("field");
Object fieldValue = field.get(myObject);
if (fieldValue instanceof String) {
    String stringValue = String.class.cast(fieldValue);
    // do something with the string value
}

I hope this helps.