如何通过单例中的字符串调用方法

时间:2014-04-19 21:31:00

标签: java

我有一个单例类,带有方法名称的字符串,我想从这个类中调用该方法。

class Foo {
   private static Foo instance;
   private String name;
   private Foo() { }
   public static getInstance() {
      if(instance == null) instance = new Foo();
      return instance;
   }
   public Foo setName(String name) {
      this.name = name;
      return this;
   }
   private void bar() {
      System.out.println("a");
   }
   public void execute() {
      // invoke "name" method here
   }
}

Foo.getInstance().setName("bar").execute();

我该怎么做?

2 个答案:

答案 0 :(得分:1)

使用Foo.getClass().getMethod(name, null).invoke(this, null)

如果您有多个具有相同名称但签名不同的方法,则需要更改getMethod的第二个参数;如果方法接受参数,则需要更改invoke

答案 1 :(得分:0)

使用反射调用:

getClass().getMethod(name).invoke(this);