使用readMethod()在java中调用对象的属性?

时间:2010-08-31 04:05:51

标签: java reflection

嗨伙计我有通过使用反射类的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");
        }

    }           

1 个答案:

答案 0 :(得分:0)

这样做 -

aTextField.setText((readMethod.invoke(ob, null)).toString());

Invoke的第二个参数是要传递给要调用的方法的参数。在您的情况下,假设它是一个read方法并且不需要参数,该参数应设置为null

toString()是必需的,因为setText需要一个String。如果您调用的方法的返回类型是String,那么您可以直接将返回值强制转换为String而不是调用toString

编辑:正如@Thilo指出的那样,由于java5 invoke支持可变数量的参数,因此您可以简单地跳过第二个参数。

aTextField.setText((readMethod.invoke(ob)).toString());