簡體   English   中英

Java-如何動態引用對象的屬性?

[英]Java—how can I dynamically reference an object's property?

在javascript中,我可以這樣做:

function MyObject(obj) {
    for (var property in obj) {
        this[property] = obj[property];
    }
}

我能用Java做點什么嗎?

class MyObject {
    String myProperty;

    public MyObject(HashMap<String, String> props) {
        // for each key in props where the key is also the name of
        // a property in MyObject, can I assign the value to this.[key]?
    }
}

並不是說我不同意喬爾的回答,但如果你基本上只是想要盡力而為,我認為這並不是那么困難。 基本上檢查它是否存在,以及是否嘗試設置。 如果它工作得很好,哦,我們嘗試過。 例如:

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

public class MyObject {

    protected String lorem;
    protected String ipsum;
    protected int integer;


    public MyObject(Map<String, Object> valueMap){
        for (String key : valueMap.keySet()){
            setField(key, valueMap.get(key));
        }
    }

    private void setField(String fieldName, Object value) {
        Field field;
        try {
            field = getClass().getDeclaredField(fieldName);
            field.set(this, value);
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        Map<String, Object> valueMap = new HashMap<String, Object>();
        valueMap.put("lorem", "lorem Value");
        valueMap.put("ipsum", "ipsum Value");
        valueMap.put("integer", 100);
        valueMap.put("notThere", "Nope");

        MyObject f = new MyObject(valueMap);
        System.out.println("lorem => '"+f.lorem+"'");
        System.out.println("ipsum => '"+f.ipsum+"'");
        System.out.println("integer => '"+f.integer+"'");
    }
}

這些答案都很糟糕,所以我覺得這個世界是一個好主意並且添加了一個不錯的答案。 首先, 如果可能的話 ,我會使用地圖:

class MyObject {

     // String myProperty; // ! not this
     HashMap<String,String> myProperties;  // use this instead

}

但是,假設您想要動態設置字段。

public MyObject(HashMap<String, String> props) {
    for (Map.Entry<String,String> entry : props.entrySet()) {
        Field field = this.getClass().getField(entry.getKey());
        field.set(this, entry.getValue());
    }
}

當然,您將需要在上面的構造函數中使用try / catch。

是的,您可以通過以下行中的某些內容進行反思:

/**
 * Returns a list of all Fields in this object, including inherited fields.
 */
private List<Field> getFields() {
    List<Field> list = new ArrayList<Field>();
    getFields(list, getClass());
    return list;
}

/**
 * Adds the fields of the provided class to the List of Fields. 
 * Recursively adds Fields also from super classes.
 */
private List<Field> getFields(List<Field> list, Class<?> startClass) {
    for (Field field : startClass.getDeclaredFields()) {
        list.add(field);
    }
    Class<?> superClass = startClass.getSuperclass();
    if(!superClass.equals(Object.class)) {
        getFields(list, superClass);
    }
}

public void setParameters(Map<String, String> props) throws IllegalArgumentException, IllegalAccessException {
    for(Field field : getFields()) {
        if (props.containsKey(field.getName())) {
            boolean prevAccessible = field.isAccessible();
            if (!prevAccessible) {
                /*
                 * You're not allowed to modify this field. 
                 * So first, you modify it to make it modifiable.
                 */
                field.setAccessible(true);
            }
            field.set(this, props.get(field.getName()));

            /* Restore the mess you made */
            field.setAccessible(prevAccessible);
        }
    }
}

但是,如果您不熟悉Java,則應盡可能避免使用此方法,因為它有點危險並且容易出錯。 例如,無法保證您嘗試設置的Field實際上是期望字符串。 如果不是這樣,您的程序將崩潰並燒毀。

好吧,如果你真的想要反思raod,那么我建議看看Introspector類並從BeanInfo獲取PropertyDescriptors列表。

暫無
暫無

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

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