在Android上调用方法

时间:2016-02-20 12:49:51

标签: java android

我有三个函数:getMeses(),getDias()和getHoras(),这些函数我想从像myMap.get(“meses”)这样的Map调用或调用它们.invoke它调用getMeses()功能

我正在尝试使用this explain Hack Reflection one。

但是当执行* .invoke方法时会出现错误:

02-20 13:36:01.153 27778-27778/com.urbanclouds.finntime E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.urbanclouds.finntime, PID: 27778
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.urbanclouds.finntime/com.urbanclouds.finntime.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object java.lang.reflect.Method.invoke(java.lang.Object, java.lang.Object[])' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2543)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2609)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1465)
at android.os.Handler.dispatchMessage(Handler.java:111)
at android.os.Looper.loop(Looper.java:207)
at android.app.ActivityThread.main(ActivityThread.java:5683)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object java.lang.reflect.Method.invoke(java.lang.Object, java.lang.Object[])' on a null object reference
at com.urbanclouds.finntime.MainActivity.onCreate(MainActivity.java:39)
at android.app.Activity.performCreate(Activity.java:6270)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1113)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2496)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2609) 
at android.app.ActivityThread.-wrap11(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1465) 
at android.os.Handler.dispatchMessage(Handler.java:111) 
at android.os.Looper.loop(Looper.java:207) 
at android.app.ActivityThread.main(ActivityThread.java:5683) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)

此方法无法在Android上使用?如果没有,我怎么能做我想做的事?

这是我的实际代码:

String time_data_keys[] = {"meses", "dias", "horas"};
HashMap<String, TextView> time_data;

@TargetApi(Build.VERSION_CODES.KITKAT)
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    int id;

    time_data = new HashMap<>();

    for ( String key : time_data_keys) {
        id =  getResources().getIdentifier(key,"id",getApplication().getPackageName());
        time_data.put(key, (TextView) findViewById(id));
    }

    Map<String, Method> methodMap = new HashMap<>();

    try {
        methodMap.put("meses", MainActivity.class.getMethod("getMeses"));
        //methodMap.put("dias", MainActivity.class.getMethod("getDias"));
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    }
/*
    try {
        methodMap.get("meses").invoke(null);
    } catch (IllegalAccessException | InvocationTargetException e) {
        e.printStackTrace();
    }
*/
    time_data.get("meses").setText(getMeses());
    //time_data.get("dias").setText(getDias());
    //time_data.get("horas").setText("Horas: %128:%32:%17");
}

private String getMeses() {

    // some stuff
    int num_meses = 2;
    String meses = String.valueOf(num_meses);

    Log.i("getMeses()", "He conseguido entrar!!");

    return getResources().getString(getResources().getIdentifier("meses","string",getApplication().getPackageName()))
            .replace("%m",meses);
}

编辑:使用此而不是null具有相同的结果

1 个答案:

答案 0 :(得分:0)

好的,谢谢Selvin我创建了一个新对象然后我可以做我想做的事情:

private class MisMetodos {

    public String getMeses() {

        // some stuff
        int num_meses = 2;
        String meses = String.valueOf(num_meses);

        Log.i("getMeses()", "He conseguido entrar!!");

        return getResources().getString(getResources().getIdentifier("meses","string",getApplication().getPackageName()))
                .replace("%m",meses);
    }

    public String getDias() {
        // some stuff
        int num_dias = 32;
        String dias = String.valueOf(num_dias);

        return getResources().getString(getResources().getIdentifier("dias","string",getApplication().getPackageName()))
                .replace("%m",dias);
    }
}

以这种方式使用反射:

MisMetodos metodos = new MisMetodos();

try {
    methodMap.put("meses", MisMetodos.class.getMethod("getMeses"));
    //methodMap.put("dias", MainActivity.class.getMethod("getDias"));
} catch (NoSuchMethodException e) {
    e.printStackTrace();
}

try {
    methodMap.get("meses").invoke(metodos);
} catch (IllegalAccessException | InvocationTargetException e) {
    e.printStackTrace();
}