How do you invoke a bean method by passing method name?


I have a bean with a bunch of setters and getters for my instance variables...

I want to create another method that will take as a paramter, the name of an instance variable, and then call the appropriate "getter" method. BUT HOW? Somehoe I have to dynamically transform the string into the method name...

public int getRedVar() {return RedVar; };
public int getBlueVar()  {returnBlueVar};

public String isValueLoaded(String varColor)
       { if get[varColor]() != null return "loaded" }

Who is Participating?
CalronConnect With a Mentor Commented:
This is a quick example similar to the one in the tutorial which would more or less do what you want:

import java.lang.reflect.*;

public class ReflectionExample {
  // have a few member variables
  private int RedVar = 7;
  private int BlueVar = 999;

  public int getRedVar() {return RedVar; };
  public int getBlueVar()  {return BlueVar; };

  public static int getColorVar(String varColor, ReflectionExample o) {
    String methodName = "get" + varColor;
    Class c = o.getClass();
    // invoking a mthdo returns an object, in our case an Integer object (int can't be returned)
    Integer result = new Integer(0);

    try {
      // the second parameter is null because the methods have no parameters
      Method m = c.getMethod(methodName, null);
      // here again, because the methods require no parameters, I can pass null as the second parameter
      result = (Integer)m.invoke(o, null);
      // catch all the exceptions that can occur
    } catch (NoSuchMethodException e) {
      System.out.println("No such Method!");
    } catch (InvocationTargetException e){
      System.out.println("Target Exception");
    } catch (IllegalAccessException e) {
      System.out.println("Illegal Access");

    return result.intValue();

  public static void main(String[] args) {
    ReflectionExample o = new ReflectionExample();
    System.out.println("RedVar = " + getColorVar("RedVar", o));
    System.out.println("BlueVar = " + getColorVar("BlueVar", o));
You will have to use reflection to really keep it dynamic. Have a look at the Java tutorial to the topic:

especially look at:

which is what you will have to implement.

Hope that helps.
keithedwardAuthor Commented:
Thanks for the references.... I am trying to understand the example, but I don't know that is does what I need.

I have a bean object with various instance varibles that have been "set". I want to act upon the same instance of the bean object by passing a method name to another method, which will then execute the method passed to it. All of this must take place upon the same bean object.

The example you gave, while it provides insight, I don't think it will be able to do what I want.....

Any other examples?
Cloud Class® Course: CompTIA Healthcare IT Tech

This course will help prep you to earn the CompTIA Healthcare IT Technician certification showing that you have the knowledge and skills needed to succeed in installing, managing, and troubleshooting IT systems in medical and clinical settings.


If I understand you problem,......

Provide the class that is going to execute the method with an interface similar to the following, (I'll assume that you do not need a return).

public void action (Object theBean, String methodName);

The action method will use the reflection API to inspect 'theBean' and to find the 'handle' of the method that matches the name provided in 'methodName.'  The action method will then use the reflection API to execute the method.

Another approach is to encapsulate the method call in a class and to pass object of that class to your executing object.

For example, pass a class similar to the following.

public class ExecuteBeanMethod {
    public void execute (Object bean) {

Your executing object will receive an object (say obj) of type Execute and execute the bean method by writing, 'obj.execute();'.

You can work with these ideas and combinations thereof to do what you want.

Ken Jones


Correct type in next to last sentence of my post ---

Your executing object will receive an object (say obj) of type ExecuteBeanMethod and execute the bean method by
writing, 'obj.execute();'.

keithedwardAuthor Commented:
I thank you all, and I understand the basics about using the reflection API....BUT I think I am going to need a actual example.....

Again, I have an instanstiated bean, and I want this same bean instance to have a method that can call any "get" method based on the string (method name) passed to it.

Question(s) below appears to have been abandoned. Your options are:
1. Accept a Comment As Answer (use the button next to the Expert's name).
2. Close the question if the information was not useful to you. You must tell the participants why you wish to do this, and allow for Expert response.
3. Ask Community Support to help split points between participating experts, or just comment here with details and we'll respond with the process.
4. Delete the question. Again, please comment to advise the other participants why you wish to do this.

For special handling needs, please post a zero point question in the link below and include the question QID/link(s) that it regards.
Please click the Help Desk link on the left for Member Guidelines, Member Agreement and the Question/Answer process.

Please click you Member Profile to view your question history and keep them all current with updates as the collaboration effort continues, to track all your open and locked questions at this site.  If you are an EE Pro user, use the Power Search option to find them.

To view your open questions, please click the following link(s) and keep them all current with updates.

To view your locked questions, please click the following link(s) and evaluate the proposed answer.

------------>  EXPERTS:  Please leave any comments regarding your closing recommendations if this item remains inactive another seven (7) days.  Also, if you are interested in the cleanup effort, please click this link
Thank you everyone.
Moderator @ Experts Exchange

P.S.  For any year 2000 questions, special attention is needed to ensure the first correct response is awarded, since they are not in the comment date order, but rather in Member ID order.
Force-accepted by
CS Moderator
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.