如何使用变量名调用java方法?

发布于 2024-10-02 01:44:06 字数 132 浏览 2 评论 0原文

假设我有 Method1(void)、Method2(void)...

有没有办法我可以选择其中一个带有变量的方法?

 String MyVar=2;
 MethodMyVar();

Say I have Method1(void), Method2(void)...

Is there a way i can chose one of those with a variable?

 String MyVar=2;
 MethodMyVar();

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

萧瑟寒风 2024-10-09 01:44:06

使用反射:

Method method = WhateverYourClassIs.class.getDeclaredMethod("Method" + MyVar);
method.invoke();

Use reflection:

Method method = WhateverYourClassIs.class.getDeclaredMethod("Method" + MyVar);
method.invoke();
め可乐爱微笑 2024-10-09 01:44:06

只有通过反思。请参阅 java.lang.reflect 包。

您可以尝试以下操作:

Method m = obj.getClass().getMethod("methodName" + MyVar);
m.invoke(obj);

如果方法有参数并且缺少各种异常处理,您的代码可能会有所不同。

但问问自己这是否真的有必要?可以改变你的设计来避免这种情况吗?反射代码很难理解,并且比仅仅调用 obj.someMethod() 慢。

祝你好运。快乐编码。

Only through reflection. See the java.lang.reflect package.

You could try something like:

Method m = obj.getClass().getMethod("methodName" + MyVar);
m.invoke(obj);

Your code may be different if the method has parameters and there's all sorts of exception handling missing.

But ask your self if this is really necessary? Can something be changed about your design to avoid this. Reflection code is difficult to understand and is slower than just calling obj.someMethod().

Good luck. Happy Coding.

仙气飘飘 2024-10-09 01:44:06

您可以使用策略设计模式以及从字符串到相应的具体策略对象的映射。这是安全有效的手段。

因此,进行 HashMap 查找。

例如,类似于:

final static YourType reciever = this;
HashMap<String,Runnable> m = new HashMap<String,Runnable> {{
    put("a", new Runnable() {
       @Override public void run () {
         reciever.a();
       }
    });
    ....
}};
// but check for range validity, etc.
m.get("a").run()

您还可以使用反射或“反转”问题并使用多态性

You could use the Strategy design pattern and a mapping from the string you have to the corresponding concrete strategy object. This is the safe and efficient means.

So, have a HashMap<String,SomeInterfaceYouWantToInvokeSuchAsRunnableWithPseudoClosures> look-up.

E.g., something along the lines of:

final static YourType reciever = this;
HashMap<String,Runnable> m = new HashMap<String,Runnable> {{
    put("a", new Runnable() {
       @Override public void run () {
         reciever.a();
       }
    });
    ....
}};
// but check for range validity, etc.
m.get("a").run()

You could also use reflection or "invert" the problem and use polymorphism

染年凉城似染瑾 2024-10-09 01:44:06

我不确定在静态方法的第一个参数为 null 的情况下,接受的答案如何适用于 method.invoke() (尽管放置虚拟值仍然有效)。根据 Java™ 教程

第一个参数是该特定对象所在的对象实例
方法将被调用。 (如果该方法是静态的,则第一个参数
应该为空。)

下面显示了一个完整的示例(Main.java),适用于静态(按类)VS 非静态(按实例),以及其他示例对于带参数的方法导入必需的类、catch异常以及超类方法示例。

import java.lang.reflect.Method;
import java.lang.reflect.InvocationTargetException;

class Love {
   protected void Method4() {
        System.out.println("calls super protected method by instance");
    }

   public void Method5() {
        System.out.println("calls super public method by instance");
    }
}

class Main extends Love {

    static void Method2(int y) {
        System.out.println("by class: " + y);
    }

    void Method3(String y) {
        System.out.println(y);
    }

    public static void main(String[] args) {

        String MyVar = "2";
        String MyAnotherVar = "3";
        String MySuperVar = "4";
        String MySuperPublicMethodVar = "5";
        Main m = new Main();

       try {
            Method method = Main.class.getDeclaredMethod("Method" + MyVar, int.class); //by class
            Method anotherMethod = m.getClass().getDeclaredMethod("Method" + MyAnotherVar, String.class); //by instance
            Method superMethod = m.getClass().getSuperclass().getDeclaredMethod("Method" + MySuperVar); //super method by instance, can be protected
            Method superPublicMethod = m.getClass().getMethod("Method" + MySuperPublicMethodVar); //getMethod() require method defined with public, so even though sublcass calls super protected method will not works
            try {
                method.invoke(null, 10000);//by class
                anotherMethod.invoke(m, "by instance"); //by instance
                superMethod.invoke(m); //super method by instance
                superPublicMethod.invoke(m); //super's public method by instance
            } catch (InvocationTargetException e) {
                throw new RuntimeException(e);
            }

       } catch (NoSuchMethodException e) {
           throw new RuntimeException(e);
       } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
       }
    }
}

输出:

$ javac Main.java
$ java Main 
by class: 10000
by instance
calls super protected method by instance
calls super public method by instance
$ 

I'm not sure how the accepted answer works for method.invoke() without first argument of static method being null(put dummy value still works though). According to The Java™ Tutorials:

The first argument is the object instance on which this particular
method is to be invoked. (If the method is static, the first argument
should be null.)

The following shows a complete examples (Main.java), for both static(by class) VS non-static(by instance), plus additional example for method with argument, import necessary class, catch exception, and also superclass method example.

import java.lang.reflect.Method;
import java.lang.reflect.InvocationTargetException;

class Love {
   protected void Method4() {
        System.out.println("calls super protected method by instance");
    }

   public void Method5() {
        System.out.println("calls super public method by instance");
    }
}

class Main extends Love {

    static void Method2(int y) {
        System.out.println("by class: " + y);
    }

    void Method3(String y) {
        System.out.println(y);
    }

    public static void main(String[] args) {

        String MyVar = "2";
        String MyAnotherVar = "3";
        String MySuperVar = "4";
        String MySuperPublicMethodVar = "5";
        Main m = new Main();

       try {
            Method method = Main.class.getDeclaredMethod("Method" + MyVar, int.class); //by class
            Method anotherMethod = m.getClass().getDeclaredMethod("Method" + MyAnotherVar, String.class); //by instance
            Method superMethod = m.getClass().getSuperclass().getDeclaredMethod("Method" + MySuperVar); //super method by instance, can be protected
            Method superPublicMethod = m.getClass().getMethod("Method" + MySuperPublicMethodVar); //getMethod() require method defined with public, so even though sublcass calls super protected method will not works
            try {
                method.invoke(null, 10000);//by class
                anotherMethod.invoke(m, "by instance"); //by instance
                superMethod.invoke(m); //super method by instance
                superPublicMethod.invoke(m); //super's public method by instance
            } catch (InvocationTargetException e) {
                throw new RuntimeException(e);
            }

       } catch (NoSuchMethodException e) {
           throw new RuntimeException(e);
       } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
       }
    }
}

Output:

$ javac Main.java
$ java Main 
by class: 10000
by instance
calls super protected method by instance
calls super public method by instance
$ 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文