开发者

Using readMethod() to invoke a property of an object in java?

Hi folks I'm having the problem of invoking a property of an object(e.g. JButton) by using readMethod() of reflection class, any ideas are much appreciated? here is the code:

 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 prob开发者_StackOverflowlem
        }
        else{
            PropertyValue.setText("???");
        }
        Method writeMethod = dpv.getWriteMethod();
        if(writeMethod != null){
            System.out.println(writeMethod);
        }
        else{
            System.out.println("Wrong");
        }

    }           


Do it like this -

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

The second argument to Invoke is the parameter you want to pass to method to be invoked. In your case, assuming its a read method and does not require parameter, this argument should be set to null.

The toString() is required as the setText expects a String. If the return type of the method you invoke is String then you may directly typecast the return value to String instead of calling toString

Edit: As @Thilo pointed out, since java5 invoke supports variable number of arguments, you can simply skip the second argument.

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜