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

标签 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");
        }

    }           

最佳答案

这样做 -

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/

相关文章:

java - Spring 文件上传失败,原因是请求的资源上存在 'Access-Control-Allow-Origin' header

java - Spring数据查询非常慢

java - 检查 15 个谜题是否可解

reflection - 不能在用反射制作的 slice 上使用范围,然后传递 json.Unmarshal

java - 反射 api 对函数的返回类型进行重载

c# - 使用反射将项目添加到通用列表/集合

java - Swing 和处理线程

java - 更改后 Firebase 数据库无法正确同步

c#-4.0 - 如何获取重载静态方法的 MethodInfo?

Java:通过反射访问对象的bean类型方法