java - Call known function (with parameters) in class whose name is defined by string variable -
i have bunch of classes of various names , each has performlogic function accepts number of preset parameters (always same):
public final class dosomeaction extends setupaction { public void performlogic(param1, param2...
i want way can call this:
string actionname = "dosomeaction"; actionname.performlogic(param1, param2...);
hope clear trying do.
thanks feedback , pointing me towards class.forname() after further research able implement following:
try { class actionclass = class.forname(blockaction); object obj = actionclass.newinstance(); class[] parametertypes = new class[2]; parametertypes[0] = string.class; parametertypes[1] = string.class; method performlogic = actionclass.getdeclaredmethod("performlogic", parametertypes); performlogic.invoke(obj, param1, param2); } catch(classnotfoundexception e) { cat.error("class not found: " + e.tostring()); }
you can use reflection
object action = ???; // perhaps need .newinstance() action class // have interface performlogic string methodname = "performlogic"; try { method method = action.getclass().getmethod(methodname, param1.class, param2.class); method.invoke(action, param1, param2); } catch (securityexception | nosuchmethodexception e) { // error method } catch (illegalargumentexception | illegalaccessexception | invocationtargetexception e) { // error call method }
Comments
Post a Comment