Using readMethod () method to call object property in java?

Hi guys I have a problem with calling an object property (e.g. JButton) using the readMethod () class of reflection, are any ideas really 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");
        }

    }           
+3
source share
1 answer

Do it like this:

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

The second argument to Invoke is the parameter that you want to pass to the called method. In your case, assuming its reading method and not requiring a parameter, this argument should be set to null.

Required toString()because setText expects a string. If the return type of the method you are calling is String, then you can directly give the return value Stringinstead of callingtoString

: @Thilo, java5 invoke , .

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

Source: https://habr.com/ru/post/1762398/


All Articles