如何使用反射在java中调用方法

Ste*_*ven 9 java reflection

如何使用反射调用带参数的方法?

我想指定这些参数的值.

pol*_*nts 15

这是一个使用包含原语的反射调用方法的简单示例.

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
    }
}
Run Code Online (Sandbox Code Playgroud)

要健壮,应该捕获和处理所有检查反射有关的异常NoSuchMethodException,IllegalAccessException,InvocationTargetException.


sum*_*rma 5

使用反射调用类方法非常简单。您需要创建一个类并在其中生成方法。就像下面这样。

package reflectionpackage;

public class My {
    public My() {
    }

    public void myReflectionMethod() {
        System.out.println("My Reflection Method called");
    }
}
Run Code Online (Sandbox Code Playgroud)

并使用反射在另一个类中调用此方法。

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);       
    } 
}
Run Code Online (Sandbox Code Playgroud)

请在此处查找更多详细信息