0

I am using the java reflection to call an API from the .class . I see my function is the list of functions listed by the .getMethods() API . The no param version works fine but the parameterised version fails .

The compilation time call for the API was

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);
    }

Here is my code that attempts to change the setAvailableValues dynamically.

 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();
                            }

I always get the following exception

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

EDIT :

I follow Mkyong wonderful tutorial on reflection How To Use Reflection To Call Java Method At Runtime

4

2 回答 2

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"}});
于 2014-10-03T04:14:07.890 回答
0

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

请参阅使用 .getDeclaredMethod 从扩展另一个答案的类中获取方法,以了解哪个应该适用。

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

有关正确的调用方式,请参阅上面的如何调用 MethodInvoke - 反射和迈克尔的回答。

于 2014-10-03T09:09:56.670 回答