2011-07-28 32 views
1

總之, 我要像做有沒有辦法在給定字段名稱的對象中獲取某個字段的值?

MyObject myObject; 

public String getField (String fieldName) { 
return myObject.fieldName; // how could I do this since fieldName is a String? 
} 

背景:

我從數據庫中使用存儲過程中獲取數據。

存儲過程基本上獲取所有列。但我希望用戶選擇在表格中顯示哪一列。

在Hibernate對象中,我有與存儲過程返回的結果集對應的所有字段。

有了用戶需要的字段列表(字符串),有沒有一種方法可以在給定字段名稱的情況下顯示Hibernate對象中相應字段的值?

+0

我知道我能做到這一點很多IF-THEN - 說明,但有沒有一個優雅的解決方案? – Jeremy

+0

字段名稱與該類中的屬性名稱相同嗎?你可以在這種情況下使用反射。 – Kaj

回答

4

您可以使用反射訪問:

public static Object getField(Object target, String fieldName) throws Exception { 
    return target.getClass().getDeclaredField(fieldName).get(target); 
} 

在你的情況,你只需使用:

myObject.getClass().getDeclaredField(fieldName).get(myObject); 

這裏的一個小測試代碼:

static class A { 
    int x = 1; 
} 

public static void main(String[] args) throws Exception { 
    System.out.println(getField(new A(), "x")); 
} 

輸出:

1 
0

使用reflection

public String getField (String fieldName, Class clazz , Object o) { 
     Field name = clazz.getField("name"); 
     name.get(o); 
} 
0

IMO對於冬眠最好是訪問throgh所述訪問器(吸氣劑)的方法的值。

我一直使用Apache的BeanUtils爲(http://commons.apache.org/beanutils/v1.8.3/apidocs/index.html

org.apache.commons.beanutils.BeanUtils.getSimpleProperty(yourEntity,fieldName); 

或者,如果你想使用比使用反射領域:

//get the field 
java.lang.reflect.Field field = yourEntity.getClass().getField(fieldName); 
//set it accessible 
boolean oldAccessible = field.isAccessible(); 
try{ 
    field.setAccessible(true); 
    Object value = field.get(yourEntity); 
    return value == null ? "" : value.toString(); 
}finally{ 
    field.setAccessible(oldAccessible) 
}; 
相關問題