how to call a java method using a variable name?

后端 未结 4 1668
傲寒
傲寒 2020-11-28 09:52

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

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

 String MyVar=2;
 MethodMyVar();
4条回答
  •  粉色の甜心
    2020-11-28 10:42

    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 look-up.

    E.g., something along the lines of:

    final static YourType reciever = this;
    HashMap m = new HashMap {{
        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

提交回复
热议问题