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

Posted on 2001-07-02
Last Modified: 2010-04-16

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" }

Question by:keithedward
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
  • 2
  • 2
  • +2

Expert Comment

ID: 6245073
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.

Author Comment

ID: 6245137
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?

Expert Comment

ID: 6245315

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

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!


Expert Comment

ID: 6245321

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();'.


Author Comment

ID: 6245535
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.


Accepted Solution

Calron earned 50 total points
ID: 6247390
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));

Expert Comment

ID: 6853786
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.

Expert Comment

ID: 6930009
Force-accepted by
CS Moderator

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

An old method to applying the Singleton pattern in your Java code is to check if a static instance, defined in the same class that needs to be instantiated once and only once, is null and then create a new instance; otherwise, the pre-existing insta…
After being asked a question last year, I went into one of my moods where I did some research and code just for the fun and learning of it all.  Subsequently, from this journey, I put together this article on "Range Searching Using Visual Basic.NET …
Viewers learn about the third conditional statement “else if” and use it in an example program. Then additional information about conditional statements is provided, covering the topic thoroughly. Viewers learn about the third conditional statement …
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:

730 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question