gene b. gene b. - 13 days ago 8
Java Question

Java Reflection - Get Current Field Value in Existing Object

I have a constructed object of the type below,

public class Form {
private String a;
private String b;
private Boolean c;

public String getA() { return a; }
public void setA (String a) { this.a = a; }
public String getB() { return b; }
public void setB (String b) { this.b = b; }
public Boolean getC() { return c; }
public void setC (Boolean c) { this.c = c; }
}


I'm using reflection to examine an existing object, e.g. this Form:
("testA", "testB", False)


How do I get the current value of a particular field, let's say
String b
?

// Assume "form" is my current Form object
Field[] formFields = form.getClass().getDeclaredFields();
if (formFields != null) {
for (Field formField : formFields) {
Class type = formField.getType();
// how do I get the current value in this current object?
}
}

Answer

Use methods of java.lang.reflect.Field:

// Necessary to be able to read a private field
formField.setAccessible(true);

// Get the value of the field in the form object
Object fieldValue = formField.get(form);