java - How to invoke a method by a string in singleton -
i have singleton class, string method's name, , want invoke method class.
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();
how can this?
use foo.getclass().getmethod(name, null).invoke(this, null)
.
you'll need change second parameter getmethod
if have several methods same name different signatures, , invoke
if method accepts parameters.
Comments
Post a Comment