Android/Java:使用反射调用方法? [英] Android/Java: Calling a method using reflection?
问题描述
我有一个名为 chooseDialog(String s, int i) 的静态方法,我想在该方法中根据提供给chooseDialog 的参数调用同一类 (Dialogs.class) 中的另一个方法.s 是所需方法的名称, i 是它的单个参数.
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 chooseDialog. s is the name of the desired method and i is it's single parameter.
我尝试了许多教程,并花了几个小时阅读该主题,但我似乎无法确定我到底需要做什么.
I have tried numerous tutorials and have spent a few hours reading up on the subject but I can't seem to get a firm grasp as to what exactly I need to do.
有什么想法吗?
谢谢!
推荐答案
为什么要调用名称传入 String 参数的方法?你不能为不同的动作创建一个常量,然后使用 switch
并在每种情况下调用带有参数 i
的方法吗?
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:如果你真的想使用反射,检索一个 Method
对象:
edit: if you really want to use reflection, retrieve a Method
object with:
Method m = YourClass.class.getMethod("method_name",new Class[] { Integer.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
这篇关于Android/Java:使用反射调用方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!