Hi, I'm having a weird problem using the invoke method of the Method class.
I've just been playing around with it to understand how to use it and I keep getting this error:
java.lang.IllegalArgumentException: object is not an instance of declaring class
Can someone please tell what's wrong with my code? It's a very simple test but it's generating that exception.
public class Human {
public void printHeight(Integer height){
System.out.println("Height is\t"+height);
}
public void printWeight(Integer weight){
System.out.println("Weight is\t"+weight);
}
public void printName(String name){
System.out.println("Name is\t"+name);
}
public void printSkill(String skill){
System.out.println("Skill is\t"+skill);
}
}
public class MethodInvoke {
public void callMethodsCreateHuman(Map<String, Object> map){
//Gets all the methods of the Human class and stores them into an array
Method[] methods = Human.class.getMethods();
//Adds methods to a map, of method name and method
Map<String, Method> methodMap = new HashMap<String, Method>();
for (Method mtd : methods) {
methodMap.put(mtd.getName(), mtd);
System.out.println("Method Added\t"+mtd.getName());
}
for (String key : map.keySet()) {
//Gets the correct setter method of Human class
//print + Name = printName
//print + Weight = printWeight
//print + Skill = printSkill
//print + Height = printHeight
String methodName = "print" + key;
//Gets the correct method to invoke by looking in the method
//map created above for its name
final Method method = methodMap.get(methodName);
//Gets the actual "Method" object
Object value = map.get(key);
if(value instanceof String){
int a = 10;
}
//Invokes the methods:
//Note: The method invoke will call the method with
//any specified number of parameters but of course
//the must match the actual number of parameters that
//method takes. if the method had 5 parameters then you
//could call put 5 arguments instead of 2 as done below
try {
method.invoke(value);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void main(String[] args){
Map<String, Object> kimmyMap = new HashMap<String, Object>();
kimmyMap.put("Name", "Kimba");
kimmyMap.put("Weight", 40);
kimmyMap.put("Height", 150);
kimmyMap.put("Skill", "CIA Intelligence Agent");
MethodInvoke mi = new MethodInvoke();
mi.callMethodsCreateHuman(kimmyMap);
}
}
Thanks heaps,
Newbie