Solved

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

Posted on 2001-07-02
8
196 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
  • 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
 
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
What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 

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 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));
  }
}
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

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
Viewers learn about the “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…
Video by: Michael
Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define …

762 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

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now