G
garfield
Here is my code (condensed):
import java.lang.reflect.*;
public class TestMethodInvocation { // 1
public static final int TESTINT = 4; // 2
public static void main(String args[]) { // 3
try {
TestMethodInvocation tmi = new TestMethodInvocation(); // 4
Object objList[] = new Object[] { tmi.getClass()
.getDeclaredField("TESTINT").get(null) }; // 5
Class clsList[] = new Class[objList.length]; // 6
for ( int i=0; i<objList.length; i++ ) {
clsList = objList.getClass(); // 7
}
Method method = tmi.getClass().getMethod("methodToInvoke",
clsList); // 8
System.out.println(method.invoke(tmi, objList)); // 9
} catch (Exception e) {
System.out.println("Nope!");
}
}
public String methodToInvoke(int i) {
return "Worked!";
}
}
What is happening is this, when line 5 executes, the class for the
integer is being converted from int to Integer. When I get the class
for that value at line 7, I get class java.lang.Integer. Subsequently
when I use it to get the Method object at line 8, I get a
MethodNotFound (or close to it) exception.
My question: using this algorhythm, how do I convert the class type in
clsList[0] from Integer.class to int.class so that I can find the
method?
Note: I am doing this because I do not know what the object types are
in my larger implementation, I have to derive them from other sources
and this seemed to be a practical way to do it until I ran into this
problem.
Thank you for any response.
import java.lang.reflect.*;
public class TestMethodInvocation { // 1
public static final int TESTINT = 4; // 2
public static void main(String args[]) { // 3
try {
TestMethodInvocation tmi = new TestMethodInvocation(); // 4
Object objList[] = new Object[] { tmi.getClass()
.getDeclaredField("TESTINT").get(null) }; // 5
Class clsList[] = new Class[objList.length]; // 6
for ( int i=0; i<objList.length; i++ ) {
clsList = objList.getClass(); // 7
}
Method method = tmi.getClass().getMethod("methodToInvoke",
clsList); // 8
System.out.println(method.invoke(tmi, objList)); // 9
} catch (Exception e) {
System.out.println("Nope!");
}
}
public String methodToInvoke(int i) {
return "Worked!";
}
}
What is happening is this, when line 5 executes, the class for the
integer is being converted from int to Integer. When I get the class
for that value at line 7, I get class java.lang.Integer. Subsequently
when I use it to get the Method object at line 8, I get a
MethodNotFound (or close to it) exception.
My question: using this algorhythm, how do I convert the class type in
clsList[0] from Integer.class to int.class so that I can find the
method?
Note: I am doing this because I do not know what the object types are
in my larger implementation, I have to derive them from other sources
and this seemed to be a practical way to do it until I ran into this
problem.
Thank you for any response.