我有下面類型的構造的對象,Java反射 - 獲取當前字段值中存在的對象
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; }
}
我使用反射來檢查現有的對象,例如此表格:("testA", "testB", False)
如何獲取特定字段的當前值,比如說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?
}
}
謝謝,這個工作,但它只返回一個字符串。我可能需要返回一個特定的對象。 –
我的歉意。我已經更新了答案。我以爲你只想要一個字符串具體。我已經更新了我的答案。如果您使用PropertyUtils(位於該庫內),則會返回一個原始對象。 – mightyrick