snippetjavaCritical
How do I invoke a Java method when given the method name as a string?
Viewed 0 times
howjavanameinvokethemethodwhengivenstring
Problem
If I have two variables:
Without knowing the class of
The method being called has no parameters, and a
Object obj;
String methodName = "getName";Without knowing the class of
obj, how can I call the method identified by methodName on it?The method being called has no parameters, and a
String return value. It's a getter for a Java bean.Solution
Coding from the hip, it would be something like:
The parameters identify the very specific method you need (if there are several overloaded available, if the method has no arguments, only give
Then you invoke that method by calling
Again, leave out the arguments in
java.lang.reflect.Method method;
try {
method = obj.getClass().getMethod(methodName, param1.class, param2.class, ..);
} catch (SecurityException e) { ... }
catch (NoSuchMethodException e) { ... }The parameters identify the very specific method you need (if there are several overloaded available, if the method has no arguments, only give
methodName).Then you invoke that method by calling
try {
method.invoke(obj, arg1, arg2,...);
} catch (IllegalArgumentException e) { ... }
catch (IllegalAccessException e) { ... }
catch (InvocationTargetException e) { ... }Again, leave out the arguments in
.invoke, if you don't have any. But yeah. Read about Java ReflectionCode Snippets
java.lang.reflect.Method method;
try {
method = obj.getClass().getMethod(methodName, param1.class, param2.class, ..);
} catch (SecurityException e) { ... }
catch (NoSuchMethodException e) { ... }try {
method.invoke(obj, arg1, arg2,...);
} catch (IllegalArgumentException e) { ... }
catch (IllegalAccessException e) { ... }
catch (InvocationTargetException e) { ... }Context
Stack Overflow Q#160970, score: 1086
Revisions (0)
No revisions yet.