?
Solved

Dynamic Methods Selection

Posted on 2000-01-17
9
Medium Priority
?
162 Views
Last Modified: 2010-04-01
Hi friends,

I would like to write a class that allow user to enter key no.  to activate the methods selected, do you think it is possible?
For eg:

I declare an ArrayList containing names string of methods: "method1", "method2", "method3".
ArrayList aList = new ArrayList() ;
aList.add("method1");
aList.add("method2");
aList.add("method3");

All the three methods got same interface, but different function.For eg.
public byte[] method1(int data)
{}

Can I select the method by this way:

public byte[] selectMethod(int ID, int data)
{
     byte[] result = ((aList.get(ID)(data)) ;
     
     return result ;

}

I got error when compiling, ')' expected.

Do you know ways to dynamically select the functions, apart from using if-else or switch-cast? As the list of methods, I hope to make it dynamic, that is the no. of methods might be changed in future. and might be downloaded from the server etc.

Please advise...Thank you very much...

regards HuangJo
0
Comment
Question by:HuangJo
9 Comments
 
LVL 1

Expert Comment

by:vivexp
ID: 2361952
Hi

In the statement  byte[] result = ((aList.get(ID)(data)) ;


The syntax of public Object get(int index);

U cant pass data here that could be the reason it is giving ')' required.

check...
0
 
LVL 16

Expert Comment

by:heyhey_
ID: 2362006
check the java.lang.reflect.* package. (and any book talking about Java Reflection)
0
 
LVL 5

Accepted Solution

by:
Jod earned 400 total points
ID: 2362217
You can identify methods from their names and from the parameters they take using reflection.

For example, if you want to find methods in an object myObject and you know the string name of the object then you can do this...

String s = "myMethod";

//this will get you all the methods in the class
Method[] theMethods = myObject.getClass().getMethods();

for (i=0; i < theMethods.length; i++) {
  if ( theMethods[i].getName().equals(s) ) {
    System.out.println("Found a matching method for: " + s);
    Class[] c = theMethods[i].getParameterTypes();
    for (j=0; j < c.length; j++) {
      System.out.println("Parameters: " + c[i].toString() );
    }
  }
}

The above will find a matching method for a given name if you only have one method with the specified name. Otherwise you will have to use the getMethod method and pass in the parameters to give a full signature to the JVM as to which method you want.

Once you have identified your method object you can invoke it and run it like this...

theMethod.invoke(myObject, new Object[] {parameters to method} );

So, to invoke a method like this:

myObject.met("String");

you would do:

String s = "String";
theMethod.invoke(myObject,new Object[] { (Object)s } )

Or something similar. Trying to remember this off hand is not that easy...
0
Never miss a deadline with monday.com

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

 

Expert Comment

by:g_senthilkumar
ID: 2362486
hi,
   You can go for Reflection,which is a technique using that we can find the information about the class at run time.Once you loaded the class file,you can find out what are all the methods available,constructors available,base class of that class,etc.And you can get the available methods and you can execute the particular method.
   In the book "Thinking in Java" by Bruceekkel,one topic "RunTime Type Identification" is there.You can find more information Reflection.

0
 
LVL 5

Expert Comment

by:Jod
ID: 2364873
Here is another example from Sun...

import java.lang.reflect.*;

public class DumpMethods {
  public static void main(String args[])
  {
    try {
      Class c = Class.forName(args[0]);
      Method m[] = c.getDeclaredMethods();
      for (int i = 0; i < m.length; i++)
        System.out.println(m[i].toString());              
    }
               
    catch (Throwable e) {
      System.err.println(e);
    }
  }
}


Invoke this program with a class name like this:

java DumpMethods java.util.Stack
0
 

Author Comment

by:HuangJo
ID: 2365792
Sorry Jod, I am not sure why the chart show only 10pts, I did awarded 100pts and it was deducted from my account too. Is it something a technical error? The last time the same thing happen too, is it normal?
0
 

Author Comment

by:HuangJo
ID: 2365794
Thank you very much to all the expert friends who answered this questions, and for all the advices that I have received.

regards Jo
0
 
LVL 5

Expert Comment

by:Jod
ID: 2366234
It's always a pleasure to help out someone who appreciates it HuangJo. We all learn a little every day.

Once the question is answered the points are awarded as you specified. The points shown then becomes the amount of points someone has to pay to get the answer if they are not myself or you for example.

If you look at all the previosly answered questions (PAQs) you will see that you cannot see the answer until you pay the appropriate number of points. To ask someone to pay 100 points for a question that has already been answered would be too much so the price changes in this case from 100 to 10.

Make sense?
0
 

Author Comment

by:HuangJo
ID: 2369307
Thank you very much, Jod. Now I understand...
0

Featured Post

Receive 1:1 tech help

Solve your biggest tech problems alongside global tech experts with 1:1 help.

Question has a verified solution.

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

Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …
Suggested Courses
Course of the Month5 days, 5 hours left to enroll

601 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