动态设置对象属性值

时间:2013-09-16 13:05:12

标签: java object properties

我是Java新手,正在尝试弄清楚如何动态设置自定义对象的属性值。我正在使用XML解析器循环遍历XML文件中的元素,我只是想将字符串设置为临时值。

public MyObject tempObj; //gets instantiated before child elements
public String tempValue; //gets set before each loop

public void stepThroughChildElement(string elementName) {
    switch (elementName) {
        case "Id":
            tempObj.Id = Integer.parseInt(tempValue);
            break;
        case "Version":
            tempObj.Version = Float.parseFloat(tempValue);
            break;
        default:
            //something like this   
            //tempObj.setProperty(elementName, tempValue);
            //or
            //tempObj[elementName] = tempValue;
            break;
    }

}

在JavaScript中,我只使用第二个示例Object["property"] = value;,但显然Java不能像那样工作。我也找到了这个Properties对象,但我不知道它是否相关。

3 个答案:

答案 0 :(得分:1)

为什么不使用Map

Map map = new HashMap();
map.put(key, value);

答案 1 :(得分:0)

你可以做这样的事情

tempObj.put("key", new Object());  // use HashtMap's put method
tempObj.setProperty("key", "value"); // use Proerties' setProperty method

答案 2 :(得分:0)

由于Java是静态类型的,因此您不能只添加这样的属性。你必须给你的对象一个Map< String,String>其他财产。

如果对象已经定义了属性,则可以对每个属性进行硬编码,或者使用java.reflection来更加动态地执行此操作。使用代码辅助并在调用tempObj.getClass()后查看可用的所有方法。您可能可以直接访问这些字段,或者您可能需要查找并调用setter方法。

相关问题