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