简体   繁体   中英

How to invoke a method in java using reflection

How can I invoke a method with parameters using reflection?

I want to specify the values of those parameters.

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 .

To call a class method using reflection is very simple. You need to create a class and generate method in it. like as follows.

package reflectionpackage;

public class My {
    public My() {
    }

    public void myReflectionMethod() {
        System.out.println("My Reflection Method called");
    }
}

and call this method in another class using reflection.

package reflectionpackage; 
import java.lang.reflect.InvocationTargetException; 
import java.lang.reflect.Method; 

public class ReflectionClass {

    public static void main(String[] args) 
    throws ClassNotFoundException, NoSuchMethodException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
        Class c=Class.forName("reflectionpackage.My");
        Method m=c.getDeclaredMethod("myReflectionMethod");
        Object t = c.newInstance();
        Object o= m.invoke(t);       
    } 
}

Find more details here .

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

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.*;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM