我有下面类型的构造的对象,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