在 activity 中按字符串名称调用函数

Calling function by string name in activity

我试图通过名称作为字符串来调用函数:

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();
}

我得到一个例外:

NoSuchMethodException com.lab.android.TabActivity.somesome [class java.lang.String]

这是我的函数:

public static void somesome() {
    Log.d("DTAG","Great Success");
}

首先,您的方法在 TabActivity class 中是静态的,因此您应该使用 getDeclaredMethod 而不是 getMethod 并且您的方法采用 0 个参数,因此您应该将 null 作为参数传递而不是 String.class,同样要调用静态方法,你应该在 invoke 中传递 null 而不是 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();
}

此代码将在日志

中打印Great Success