2014-10-03 28 views
0

我正在使用java反射從.class調用API。我看到我的函數是.getMethods()API列出的函數列表。沒有參數版本可以正常工作,但參數化版本失敗。調用函數的java反射

的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

回答

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