
Java反射机制可以在程序运行时动态地获取类的信息,下面详解5种常用的Java反射调用方法@mikechen
1.调用无参方法
使用Method对象的invoke()方法调用无参方法,不需要传递任何实参。
// 获取Class对象
Class<?> clazz = Class.forName("com.mikechen.MyClass");
// 调用无参方法
Method method1 = clazz.getDeclaredMethod("testMethod1");
Object result1 = method1.invoke(clazz.newInstance());
System.out.println(result1);
2.调用有参方法
使用Method对象的invoke()方法调用有参方法,需要传递方法的实参。
// 获取Class对象
Class<?> clazz = Class.forName("com.mikechen.MyClass");
Method method2 = clazz.getDeclaredMethod("testMethod2", String.class);
Object result2 = method2.invoke(clazz.newInstance(), "Hello World");
System.out.println(result2);
3.调用静态方法
首先需要获取包含静态方法的类的Class对象。
Class<?> clazz = Class.forName("com.mikechen.MyClass");
然后获取方法对象,使用Class类的getMethod方法获取要调用的静态方法对象。
Method method = clazz.getMethod("myStaticMethod", String.class, int.class);
使用Method类的invoke方法调用静态方法:
Object result = method.invoke(null, "Hello", 123);
由于静态方法不依赖于对象,因此可以将第一个参数设置为null。
4.调用私有方法
Java反射调用私有方法需要使用getDeclaredMethod方法来获取指定名称和参数类型的私有方法对象。
与公共方法不同的是,私有方法需要使用setAccessible方法将可访问性设置为true,才能够通过反射机制调用。
import java.lang.reflect.Method;
public class MyClass {
private void myPrivateMethod(String name) {
System.out.println("Hello " + name);
}
}
public class Main {
public static void main(String[] args) throws Exception {
MyClass obj = new MyClass();
Class<?> clazz = obj.getClass();
Method method = clazz.getDeclaredMethod("myPrivateMethod", String.class);
method.setAccessible(true);
method.invoke(obj, "John");
}
}
5.调用父类方法
Java反射调用父类方法需要使用getSuperclass方法获取父类的Class对象,然后使用getMethod或getDeclaredMethod方法获取父类中定义的方法对象。
import java.lang.reflect.Method;
public class ParentClass {
public void parentMethod() {
System.out.println("Parent method called");
}
}
public class ChildClass extends ParentClass {
@Override
public void parentMethod() {
System.out.println("Child method called");
}
}
public class Main {
public static void main(String[] args) throws Exception {
ChildClass obj = new ChildClass();
Class<?> clazz = obj.getClass();
Class<?> superClass = clazz.getSuperclass();
Method method = superClass.getDeclaredMethod("parentMethod");
method.invoke(obj);
}
}
以上就是Java反射方法详解,更多Java反射请查看:Java反射详解(万字图文全面总结)
mikechen睿哥
10年+大厂架构经验,资深技术专家,就职于阿里巴巴、淘宝、百度等一线互联网大厂。