I trying to call a function by names as a string:
Method method = null;
try {
method = Class.forName("com.lab.android.TabActivity").getMethod(item,String.class);
method.invoke(this, null);
} catch (NoSuchMethodException e) {
Log.e("DTAG","NoSuchMethodException " e.getMessage());
e.printStackTrace();
} catch (ClassNotFoundException e) {
Log.e("DTAG","ClassNotFoundException " e.getMessage());
e.printStackTrace();
} catch (IllegalAccessException e) {
Log.e("DTAG","IllegalAccessException " e.getMessage());
e.printStackTrace();
} catch (InvocationTargetException e) {
Log.e("DTAG","InvocationTargetException " e.getMessage());
e.printStackTrace();
}
I get an exeptioon:
NoSuchMethodException com.lab.android.TabActivity.somesome [class java.lang.String]
This is the function in my ativity:
public static void somesome() {
Log.d("DTAG","Great Success");
}
CodePudding user response:
First, your method is static in TabActivity class so you should use getDeclaredMethod
not getMethod
and also your method takes 0 parameters so you should pass null as a parameter not String.class
, also to call the static method your should pass null in invoke not this
Method method = null;
String methodName = "somesome";
try {
method = Class.forName(TabActivity.class.getName()).getDeclaredMethod(methodName, null);
method.invoke(null, null);
} catch (NoSuchMethodException e) {
Log.e("DTAG","NoSuchMethodException " e.getMessage());
e.printStackTrace();
} catch (ClassNotFoundException e) {
Log.e("DTAG","ClassNotFoundException " e.getMessage());
e.printStackTrace();
} catch (IllegalAccessException e) {
Log.e("DTAG","IllegalAccessException " e.getMessage());
e.printStackTrace();
} catch (InvocationTargetException e) {
Log.e("DTAG","InvocationTargetException " e.getMessage());
e.printStackTrace();
}
This code will print Great Success
in the log