Solved

Java reflection - Invoking Methods with a Variable Number of Arguments

Posted on 2008-10-30
6
452 Views
Last Modified: 2013-11-23
Hi,

My scenario is such that i have a class that receives the name of a method and the qualified name of the class that contains it. Using this info i get a reference to the method. My problem arises when i want to call that method and pass it parameters. I need to create this class such that i am able to call different methods with varying numbers of params. These params will all be numbers.

e.g. public double meth1(double 1,double 2){}
       public double meth2(double 1,double 2,double 3){}

I know its possible to to do this if all my methods had an array as a param but realistically i cant do this.

Anybody have a solution?

Thanks in advance
public NelderMead(){}

	public double run(String qualifiedClassName,String methodName, double[] startparams,int paranum,double TOL){

		

		

		

		//start reflection

		try{

			Class<?> c = Class.forName(qualifiedClassName);

			

			Method meth=null;;

			

			Method[] allMethods = c.getDeclaredMethods();

			for (Method m : allMethods) {

				String mname = m.getName();

				if (mname.equals(methodName))

					meth=m;	

			}

			

			meth.invoke(startparams);

		}

		catch(ClassNotFoundException e){}

		//catch(NoSuchMethodException n){}

		catch(InvocationTargetException in){Throwable cause = in.getCause();

	    err.format("invocation of %s failed: %s%n","", cause.getMessage());}

		catch(IllegalAccessException il){Throwable cause = il.getCause();

	    err.format("invocation of %s failed: %s%n","", cause.getMessage());}

Open in new window

0
Comment
Question by:billyleo
  • 4
  • 2
6 Comments
 
LVL 59

Expert Comment

by:Kevin Cross
ID: 22840782
Here is the example from Java website on reflection:
http://java.sun.com/docs/books/tutorial/reflect/member/methodInvocation.html

If you have any more questions on it, please post back.
0
 
LVL 59

Expert Comment

by:Kevin Cross
ID: 22840839
You can also look for the method by the number of parameters and their types if you actual know coming in what method you are looking for and its signature or at least the parameters you have to pass to it.

try {

                Class c = Class.forName("MainClass");

                Class[] parameterTypes = new Class[2];

                parameterTypes[0] = double.class;

                parameterTypes[1] = double.class;

                c.getMethod("meth1", parameterTypes);

            } catch (ClassNotFoundException e) {

                // TODO Auto-generated catch block

                e.printStackTrace();

            } catch (SecurityException e) {

                // TODO Auto-generated catch block

                e.printStackTrace();

            } catch (NoSuchMethodException e) {

                // TODO Auto-generated catch block

                e.printStackTrace();

            }

Open in new window

0
 

Author Comment

by:billyleo
ID: 22841029
thanks for the input but my problem arises after i get the method that i want to invoke.

I have been reading the link you posted but they only seem to show you how to invoke methods like a 'main' method that thats in an array of params!

Cheers
0
DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

 
LVL 59

Expert Comment

by:Kevin Cross
ID: 22841545
I was trying to simplify and my code example was in a class called MainClass.

Here is a better example:
import java.lang.reflect.InvocationTargetException;

import java.lang.reflect.Method;

import java.util.ArrayList;

import java.util.List;
 
 

public class MyClass {
 

    public MyClass() {

        

    }

    

    public static void main(String args[]) {

        MyClass instance = new MyClass();

        Class c = instance.getClass();

        

        if (args == null || args.length != 2) {

            args = new String[2];

            args[0] = "Test";

            args[1] = "Param";

        }

        List<Class> paramTypes = new ArrayList<Class>();

        for (Object o : args) {

            paramTypes.add(o.getClass());

        }
 

        Method meth=null;;

        

        Method[] allMethods = c.getDeclaredMethods();

        for (Method m : allMethods) {

            String mname = m.getName();

            if (mname.equals("meth1"))

                meth=m; 

        }

        

        try {

            Object o = meth.invoke(instance, args);

            System.out.println(o.toString());

        } catch (IllegalArgumentException e) {

            // TODO Auto-generated catch block

            e.printStackTrace();

        } catch (IllegalAccessException e) {

            // TODO Auto-generated catch block

            e.printStackTrace();

        } catch (InvocationTargetException e) {

            // TODO Auto-generated catch block

            e.printStackTrace();

        }
 

    }
 

    public String meth1(String param1, String param2) {

        System.out.println("Param1: " + param1);

        System.out.println("Param2: " + param2);

        return "Hello World";

    }

}

Open in new window

0
 
LVL 59

Accepted Solution

by:
Kevin Cross earned 500 total points
ID: 22841586
If everything else matches what you have, the net is that I think you need an instance of class holding the method to invoke against.
0
 

Author Closing Comment

by:billyleo
ID: 31511645
Thanks - hopefully this will work - i'll let you know when i get a chance to implement it.

Cheers
0

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
Systems talking to each other 5 124
backtracking recursion  code 19 53
Java DateChooser? 3 29
xampp tool 12 24
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…
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…
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:

911 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

22 Experts available now in Live!

Get 1:1 Help Now