import java.lang.reflect.Method;
public class ReflectionExample {
public static void main(String[] args) {
try {
// 获取 Class 对象
Class<?> clazz = Class.forName("java.util.ArrayList");
// 创建对象实例
Object instance = clazz.getDeclaredConstructor().newInstance();
// 获取指定方法
Method addMethod = clazz.getMethod("add", Object.class);
// 调用方法
addMethod.invoke(instance, "Hello, Reflection!");
// 获取所有方法
Method[] methods = clazz.getMethods();
for (Method method : methods) {
System.out.println(method.getName());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Class.forName 方法获取类的 Class 对象。这里我们使用了 java.util.ArrayList 作为示例。getDeclaredConstructor().newInstance() 来创建类的实例。getMethod 方法获取类中的特定方法,这里获取的是 ArrayList 的 add 方法。invoke 方法来调用获取到的方法,并传递参数。getMethods 方法获取类中所有的公共方法,并打印出来。这个例子展示了如何使用 Java 反射机制来动态地操作类和方法。
上一篇:java enum
下一篇:java获取时间戳
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站