簡體   English   中英

無論如何在給定字段名稱的情況下獲取對象中某個字段的值?

[英]Is there anyway to get the value of a certain field in an object given the field name?

簡而言之,我想做點什么

MyObject myObject;

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

背景:

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

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

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

使用用戶想要的字段列表(字符串),有沒有辦法在給定字段名稱的情況下顯示Hibernate對象中相應字段的值?

您可以使用反射訪問它:

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

使用反射

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

IMO for hibernate最好是訪問accessser(getter)方法的值。

我總是使用Apache BeanUtils( http://commons.apache.org/beanutils/v1.8.3/apidocs/index.html

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

或者如果您想使用該字段而不是使用Reflection:

//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)
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM