大家好,我在使用反射类的 readMethod() 调用对象的属性(例如 JButton)时遇到问题,有什么想法值得赞赏吗? 这是代码:
private void PropertySelectedFromList(java.awt.event.ActionEvent evt) {
// add code here
String propertyName = (String)PropertyList.getSelectedItem();
PropertyType.setEnabled(true);
PropertyType.setText("Text" + propertyName);
PropertyValue.setEnabled(true);
PropertyDescriptor dpv = PropValue(props, propertyName);
Method readMethod = dpv.getReadMethod();
if(readMethod != null){
String obtName = (String) ObjectList.getSelectedItem();
Object ob = FindObject(hm, obtName);// retrieving object from hashmap
aTextField.setText(readMethod.invoke(ob, ???));<----------here is the problem
}
else{
PropertyValue.setText("???");
}
Method writeMethod = dpv.getWriteMethod();
if(writeMethod != null){
System.out.println(writeMethod);
}
else{
System.out.println("Wrong");
}
}
最佳答案
这样做 -
aTextField.setText((readMethod.invoke(ob, null)).toString());
Invoke 的第二个参数是要传递给要调用的方法的参数。在您的情况下,假设它是一个读取方法并且不需要参数,则该参数应设置为 null
。
需要 toString()
,因为 setText 需要一个字符串。如果您调用的方法的返回类型是String
,那么您可以直接将返回值类型转换为String
,而不是调用toString
编辑:正如@Thilo 指出的,由于 java5 invoke
支持可变数量的参数,因此您可以简单地跳过第二个参数。
aTextField.setText((readMethod.invoke(ob)).toString());
关于java - 在java中使用readMethod()调用对象的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3605964/