Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (4k points)

If I have two variables:

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 Stringreturn value. It's a getter for a Java bean.

1 Answer

0 votes
by (46k points)

From Java Reflection, you can use method invocation to call the method identified by methodName on it without knowing the class of the object:

java.lang.reflect.Method method;

try {

  method = obj.getClass().getMethod(methodName, param1.class, param2.class, ..);

} catch (SecurityException e) { ... }

  catch (NoSuchMethodException e) { ... }

The parameters recognize the very specific method we need (if there are many overloaded available, if the method has no arguments, only give methodName).

 

To invoke that method, use:

try {

  method.invoke(obj, arg1, arg2,...);

} catch (IllegalArgumentException e) { ... }

  catch (IllegalAccessException e) { ... }

  catch (InvocationTargetException e) { ... }

In case if there aren't any arguments in .invoke,  then exclude it. 

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Oct 27, 2019 in Java by Shubham (3.9k points)
Welcome to Intellipaat Community. Get your technical queries answered by top developers!

30.5k questions

32.6k answers

500 comments

108k users

Browse Categories

...