2016-11-25 75 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