Set field value
import java.awt.Rectangle;
import java.lang.reflect.Field;
public class Main {
public static void main(String[] args) {
Rectangle r = new Rectangle(100, 20);
System.out.println("original: " + r.toString());
modifyWidth(r, new Integer(300));
System.out.println("modified: " + r.toString());
}
static void modifyWidth(Rectangle r, Integer widthParam) {
Field widthField;
Integer widthValue;
Class c = r.getClass();
try {
widthField = c.getField("width");
widthField.set(r, widthParam);
} catch (NoSuchFieldException e) {
System.out.println(e);
} catch (IllegalAccessException e) {
System.out.println(e);
}
}
}
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