Get Field value by field name
import java.lang.reflect.Field;
public class Main {
public static void main(String[] unused) throws Exception{
Object o = new MyClass();
System.out.println(intFieldValue(o, "currentYear"));
}
static int intFieldValue(Object o, String name) throws Exception{
Class c = o.getClass();
Field fld = c.getField(name);
int value = fld.getInt(o);
return value;
}
}
class MyClass {
public int currentYear = 2012;
}
Home
Java Book
Runnable examples
Java Book
Runnable examples
Reflection Field:
- Get all fields
- Get all Declared Fields
- Get annotations for a Field
- Get "public static final" field
- Get specific fields
- Get Field value by field name
- Get fields for super class
- Get Inherited Methods and fields
- Get Type of the field or return type of a method.
- Field modifiers: isSynthetic, isEnumConstant
- Set field value
- Set null to a field value
- Set private field value