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
  • 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

Is Your AD Toolbox Looking More Like a Toybox?

Managing Active Directory can get complicated.  Often, the native tools for managing AD are just not up to the task.  The largest Active Directory installations in the world have relied on one tool to manage their day-to-day administration tasks: Hyena. Start your trial today.


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

3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Python Assistance 7 80   readLine()  //returns the entire file ? 4 73
servlet  URL Rewriting 1 36
tomcat startup error 5 63
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 …
Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.
This video teaches viewers about errors in exception handling.

770 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