2016-11-25 61 views
0

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

回答

3

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); 
1

这是我使用外部库的大支持者的情况。 Apache Commons BeanUtils非常适合这种用途,并且隐藏了很多核心的java.lang.reflect复杂性。你可以在这里找到它:http://commons.apache.org/proper/commons-beanutils/

使用BeanUtils的,以满足您的需要的代码将是如下:

Object valueOfB = PropertyUtils.getProperty(formObject, "b"); 

使用的BeanUtils的另一个好处是,它所有的检查,以确保您有适用于“b”的访问器方法 - getB()。 BeanUtils库中还有其他实用程序方法,使您可以处理各种Java bean属性操作。

+0

谢谢,这个工作,但它只返回一个字符串。我可能需要返回一个特定的对象。 –

+0

我的歉意。我已经更新了答案。我以为你只想要一个字符串具体。我已经更新了我的答案。如果您使用PropertyUtils(位于该库内),则会返回一个原始对象。 – mightyrick