Get field value with Reflection
Object get(Object obj)
- Returns field value
boolean getBoolean(Object obj)
- Gets field value as boolean.
byte getByte(Object obj)
- Gets field value as byte.
char getChar(Object obj)
- Gets field value as char.
double getDouble(Object obj)
- Gets field value as double.
float getFloat(Object obj)
- Gets field value as float.
Type getGenericType()
- Returns a Type object that represents the declared type for the field represented by this Field object.
int getInt(Object obj)
- Gets field value as int.
long getLong(Object obj)
- Gets field value as long.
short getShort(Object obj)
- Gets field value as short.
import java.awt.Rectangle;
import java.lang.reflect.Field;
public class Main {
public static void main(String[] args) {
Rectangle r = new Rectangle(100, 325);
Class c = r.getClass();
try {
Field heightField = c.getField("height");
Integer heightValue = (Integer) heightField.get(r);
System.out.println("Height: " + heightValue.toString());
} catch (NoSuchFieldException e) {
System.out.println(e);
} catch (SecurityException e) {
System.out.println(e);
} catch (IllegalAccessException e) {
System.out.println(e);
}
}
}
Home
Java Book
Reflection
Java Book
Reflection
Field:
- Field Reflection
- Get the field modifiers, name and type
- Get field value with Reflection
- Set field value with Reflection