?
Solved

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

Posted on 2001-07-02
8
Medium Priority
?
218 Views
Last Modified: 2010-04-16
Hello,

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


Thanks!
0
Comment
Question by:keithedward
[X]
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
8 Comments
 
LVL 5

Expert Comment

by:Calron
ID: 6245073
You will have to use reflection to really keep it dynamic. Have a look at the Java tutorial to the topic:

http://java.sun.com/docs/books/tutorial/reflect/index.html

especially look at:

http://java.sun.com/docs/books/tutorial/reflect/object/invoke.html

which is what you will have to implement.

Hope that helps.
0
 

Author Comment

by:keithedward
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?
0
 
LVL 4

Expert Comment

by:k.jones
ID: 6245315
keithedward,

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) {
        bean.<bean-method-name>(<parameters>);
    }
}

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.

Cheers,
Ken Jones

Cheers,
Ken
0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
LVL 4

Expert Comment

by:k.jones
ID: 6245321
keithedward,

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

Cheers,
Ken
0
 

Author Comment

by:keithedward
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.



0
 
LVL 5

Accepted Solution

by:
Calron earned 200 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));
  }
}
0
 
LVL 1

Expert Comment

by:Moondancer
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.
http://www.experts-exchange.com/jsp/qList.jsp?ta=commspt
 
Please click the Help Desk link on the left for Member Guidelines, Member Agreement and the Question/Answer process.  http://www.experts-exchange.com/jsp/cmtyHelpDesk.jsp

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.
http://www.experts-exchange.com/questions/Q.11535258.html
http://www.experts-exchange.com/questions/Q.11680199.html
http://www.experts-exchange.com/questions/Q.11968358.html
http://www.experts-exchange.com/questions/Q.20101682.html
http://www.experts-exchange.com/questions/Q.11282198.html
http://www.experts-exchange.com/questions/Q.20144553.html
http://www.experts-exchange.com/questions/Q.20274598.html


To view your locked questions, please click the following link(s) and evaluate the proposed answer.
http://www.experts-exchange.com/questions/Q.11290237.html
http://www.experts-exchange.com/questions/Q.20273159.html

PLEASE DO NOT AWARD THE POINTS TO ME.  
 
------------>  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 http://www.experts-exchange.com/jsp/qManageQuestion.jsp?ta=commspt&qid=20274643
 
Thank you everyone.
 
Moondancer
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.
0
 
LVL 5

Expert Comment

by:Netminder
ID: 6930009
Force-accepted by
Netminder
CS Moderator
0

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

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

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…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
This video teaches viewers about errors in exception handling.
How to fix incompatible JVM issue while installing Eclipse While installing Eclipse in windows, got one error like above and unable to proceed with the installation. This video describes how to successfully install Eclipse. How to solve incompa…
Suggested Courses
Course of the Month9 days, 5 hours left to enroll

765 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