我是新来的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对象,但我不知道它是否相关。
或者使用'Map'作为[其他](http://stackoverflow.com/a/18828848/2071828)有建议。要获得更灵活的方法,请使用JAXB等XML绑定框架。 –
不要试图像使用另一种松散类型的语言一样使用Java。 – Bart
我正在使用SAX http://docs.oracle.com/javase/tutorial/jaxp/sax/parsing.html – tedski