views:

30

answers:

1

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

    }           
A: 

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());
Gopi
Thank you for your help
HAMID
why not just readMethod.invoke(ob) ?
Thilo
The invoke method accepts two argument, it complaints when you want to pass only 'ob'
HAMID
Since Java5, Method.invoke accepts varargs: http://download-llnw.oracle.com/javase/6/docs/api/java/lang/reflect/Method.html#invoke%28java.lang.Object,%20java.lang.Object...%29
Thilo
@Thilo yes I missed that out! Will update my answer. Thanks for suggestion.
Gopi