【问题标题】:java reflection calling a functionjava反射调用函数
【发布时间】:2014-10-03 17:09:56
【问题描述】:

我正在使用 java 反射从 .class 调用 API。我看到我的函数是 .getMethods() API 列出的函数列表。无参数版本工作正常,但参数化版本失败。

API 的编译时间调用是

public static class CapabilitiesEditor  extends ComboBoxPropertyEditor  {
    public CapabilitiesEditor() {
        super();
        print(); // Call to print if fine . 
        setAvailableValues(new String[] { "High", "Medium", "Low", "None", }); // I want call this one . Fails
        Icon[] icons = new Icon[4];
        Arrays.fill(icons, UIManager.getIcon("Tree.openIcon"));
        setAvailableIcons(icons);
    }

这是我尝试动态更改 setAvailableValues 的代码。

 Class<?> cls;
    // Paremeterized call 
    Class[] paramObject = new Class[1]; 
    paramObject[0] = Object[].class; // Function takes a single parameter of type Object[]
    Object[] params = new String[] { "H", "M", "L", "N" };

    // no paramater version
    Class noparams[] = {};

    try { 

    cls = Class.forName("com.app.services.prop.system.SystemTopologyBean$CapabilitiesEditor");                                  Object obj = cls.newInstance();   

    for(Method method : cls.getMethods()){
        System.out.println("method = " + method.getName());
    }
    // WORKS
    Method method = cls.getDeclaredMethod("print", noparams);  
    method.invoke(obj, null);

    // **DOES NOT WORK** 
    Method method = cls.getDeclaredMethod("setAvailableValues", paramObject);
    method.invoke(obj, params);

    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | NoSuchMethodException | SecurityException | IllegalArgumentException | InvocationTargetException e2) {
                                // TODO Auto-generated catch block
                                e2.printStackTrace();
                            }

我总是得到以下异常

java.lang.NoSuchMethodException: com.app.services.prop.system.SystemTopologyBean$CapabilitiesEditor.setAvailableValues([Ljava.lang.Object;)

编辑:

我关注 Mkyong 关于反射的精彩教程How To Use Reflection To Call Java Method At Runtime

【问题讨论】:

    标签: java reflection javarebel


    【解决方案1】:

    要检索您的方法,然后调用它,您需要这样做:

    Class cls = Class.forName("com.app.services.prop.system.SystemTopologyBean$CapabilitiesEditor");
    Object obj = cls.newInstance();
    Method method = cls.getDeclaredMethod("setAvailableValues", new Class[] {String[].class});
    method.invoke(obj, new Object[] {new String[] {"Foo", "Bar"}});
    

    【讨论】:

      【解决方案2】:

      所以这里有两个问题阻止我访问该功能。小心我应该使用getMethod 而不是getDeclaredMethod

      请参阅Using .getDeclaredMethod to get a method from a class extending another 答案以了解应适用的答案。

      在调用 method.invoke 函数时也要非常小心,尤其是第二个参数。

      请参阅上面的How to call MethodInvoke - reflection 和迈克尔的回答,了解正确的呼叫方式。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-07-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-05-23
        相关资源
        最近更新 更多