Reputation: 286
I keep getting this error message:
06-13 18:53:33.839: W/System.err(19893): java.lang.NoSuchMethodException: showIt
06-13 18:53:33.839: W/System.err(19893): at java.lang.ClassCache.findMethodByName(ClassCache.java:247)
06-13 18:53:33.839: W/System.err(19893): at java.lang.Class.getDeclaredMethod(Class.java:731)
I'm sure my method exists, I try to start from within a asynctask. This is the method:
public static void showIt(String[] result) {
And this is the code I've tried:
try {
Class<?> p = Class.forName(executeClass);
Object t = p.newInstance();
Method m = p.getDeclaredMethod(executeMethod, p);
m.invoke(t, result);
} catch (Exception e) {
e.printStackTrace();
}
Upvotes: 1
Views: 347
Reputation: 5614
You got two mistakes here:
.
public class Main {
public static void main(String[] args){
try {
Class<?> p = Main.class;
String[] arguments = {"ciao"};
Method m = p.getDeclaredMethod("showIt",String[].class);
m.invoke(null, arguments);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void showIt(String[] result) {
System.out.println(result[0]);
}
}
Upvotes: 0
Reputation: 3399
Three problems ...
getDeclaredMethod second argument must be an array of parameters classes of the showIt method.
Because the method is static, it is useless to pass an object to the first argument of invoke method.
Because the invoke method is varargs, result must be wrapped into a Object[] in order to be passed as excepted.
Finally, here is a working code snipet.
String[] result = new String[] { "res" };
Class<?> p = Class.forName(executeClass);
Method m = p.getDeclaredMethod("showIt", result.getClass());
m.invoke(null, new Object[] {result});
Upvotes: 1
Reputation: 71909
Given executeClass = "YourClass"
and executeMethod = "showIt"
, p.getDeclaredMethod(executeMethod, p)
is trying to find showIt(YourClass arg)
, but you have showIt(String[] arg)
.
Try p.getDeclaredMethod(executeMethod, String[].class)
.
Upvotes: 1