reflection - How do I invoke a Java method when given the method name as a string? -


if have 2 variables:

object obj; string methodname = "getname"; 

without knowing class of obj, how can call method identified methodname on it?

the method being called has no parameters, , string return value. it's a getter java bean.

coding hip, like:

java.lang.reflect.method method; try {   method = obj.getclass().getmethod(methodname, param1.class, param2.class, ..); } catch (securityexception e) { ... }   catch (nosuchmethodexception e) { ... } 

the parameters identify specific method need (if there several overloaded available, if method has no arguments, give methodname).

then invoke method calling

try {   method.invoke(obj, arg1, arg2,...); } catch (illegalargumentexception e) { ... }   catch (illegalaccessexception e) { ... }   catch (invocationtargetexception e) { ... } 

again, leave out arguments in .invoke, if don't have any. yeah. read java reflection


Comments

Popular posts from this blog

sublimetext3 - what keyboard shortcut is to comment/uncomment for this script tag in sublime -

dataset - MPAndroidchart returning no chart Data available -

post - imageshack API cURL -