是否可以根据X值运行methodnameX?

时间:2017-10-22 07:38:38

标签: java methods

如果

中有3种方法
public class Hero extends GameCharacter {

public void test1(){}; 
public void test2(){}; 
public void test3(){};

是否可以在

中运行它
public class MainClass extends ApplicationAdapter implements InputProcessor {
@Override
public void create () {
private Hero mainHero;
For (int x = 0; x < 0; x++)
    ....

运行

mainhero.testx

3 个答案:

答案 0 :(得分:3)

这种情况适合Strategy Pattern。基本上你有一个功能的变化,所以你创建一个接口来执行它,并创建它的多个实现。它可能看起来像这样:

package test;

public class Test {

    public static interface TestStrategy {
        void test();
    }

    public static class Test1 implements TestStrategy {

        @Override
        public void test() {
            System.out.println("1");
        }

    }

    public static class Hero {
        TestStrategy test[] = new TestStrategy[]{
            //either use defined class
            new Test1(),
            //or inline
            () -> {System.out.println("2");}
        };
    }

    public static void main(String[] args) {
        Hero hero = new Hero();
        for (int i = 0; i < hero.test.length; i++) {
            hero.test[i].test();
        }
    }
}

答案 1 :(得分:1)

您可以使用反射,但您应该为此评估更好的模式。

替代解决方案包括

条件

public void test(int x){
    switch (x) {
       case 1:
          // Things for x == 1
          break;
    }
}; 

OOP,因为你有不同类型的英雄

public abstract class Hero extends GameCharacter {
    public abstract void test();
}

public class Hero1 extends Hero {
    @Override
    public void test() {}
}

...

List<Hero> heroes  = ... ;
heroes.add(new Hero1());
for (Hero h : heroes) { h.test(); }

或者,只需通过独立的单元测试方法单独调用所有测试方法。

答案 2 :(得分:0)

如前所述,您可以使用反射。此示例使用反射来演示。

public void callYourClassMethod(String x) {
  try {
    YourClass yourClass = new YourClass()
    Method method = YourClass.class.getDeclaredMethods("methodname" + x);
    method.setAccessible(true); // Only needed if it's not accessible from calling class.
    method.invoke(yourClass); // Assuming your method doesn't take any arguments.
  } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
    System.err.println("Method methodname" + x + "is not declared.");
    e.printStackTrace();
  }
}