Android/Java: Calling a method using reflection?

后端 未结 4 1340
轻奢々
轻奢々 2020-12-10 15:26

I have a static method titled chooseDialog(String s, int i) in which I want to call another method within the same class (Dialogs.class) based on the parameters provided to

4条回答
  •  悲&欢浪女
    2020-12-10 15:47

    Why do you want to call a method with name passed in a String parameter? Cannot you create a constants for different actions, then use switch and in each case call the method with parameter i?

    You will have the benefit of compiler checking your code for errors.

    edit: if you really want to use reflection, retrieve a Method object with:

    Method m = YourClass.class.getMethod("method_name",new Class[] { Integer.class }) 
    

    I guess Integer.class might work. Then invoke the metod as

    m.invoke(null,123); //first argument is the object to invoke on, ignored if static method
    

提交回复
热议问题