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
Post a Comment