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. You can then cast the returned value to the appropriate type.

Here is an example of how to do this:

class MyClass<T> {
    public T field;
}

// ...

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

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
}

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 also use the getType() method of the Field class to get the Class object for the field type, and then use the cast() method to cast the field value to the appropriate type.

Here is an example:

Field field = MyClass.class.getDeclaredField("field");
Class<?> fieldType = field.getType();
if (fieldType == String.class) {
    String stringValue = fieldType.cast(field.get(myObject));
    // do something with the string value
}

I hope this helps.