views:

151

answers:

4

Hi,

How can I invoke a method with parameters using reflections?

I want to the values to those parameters. Can somebody help?

+1  A: 

In the java Reflection tutorial search for Invoking Methods by Name

saugata
A: 

You can use getClass in any Object to discover its class. Then you can use getMethods to discover all the available methods. Once you have the correct method you can call invoke with any number of parameters

leonm
any links showing example
Steven
A: 

this is the easiest way I know of, it needs to be surrounded with try & catch:

Method m = .class.getDeclaredMethod("", arg_1.class, arg_2.class, ... arg_n.class); result = () m.invoke(null,(Object) arg_1, (Object) arg_2 ... (Object) arg_n);

this is for invoking a static method, if you want to invoke a non static method, you need to replace the first argument of m.invoke() from null to the object the underlying method is invoked from.

don't forget to add an import to java.lang.reflect.*;

Shuky Kappon
what if i am using primitives
Steven
@Shuky: why casting the arguments to Object?
Carlos Heuberger
@Seteven, Carlos Heuberger: the casting is not required, I just meant they cannot be primitives (instead of int, use Integer, etc)
Shuky Kappon
+2  A: 

Here's a simple example of invoking a method using reflection involving primitives.

import java.lang.reflect.*;

public class ReflectionExample {
    public int test(int i) {
        return i + 1;
    }
    public static void main(String args[]) throws Exception {
        Method testMethod = ReflectionExample.class.getMethod("test", int.class);
        int result = (Integer) testMethod.invoke(new ReflectionExample(), 100);
        System.out.println(result); // 101
    }
}

To be robust, you should catch and handle all checked reflection-related exceptions NoSuchMethodException, IllegalAccessException, InvocationTargetException.

polygenelubricants
@polygenelubricants-thanks
Steven