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();
// 获取目标方法的对象,这里以 add 方法为例
Method addMethod = clazz.getMethod("add", Object.class);
// 调用目标方法
Boolean result = (Boolean) addMethod.invoke(instance, "Hello, Reflection!");
// 输出调用结果
System.out.println("Method invocation result: " + result);
// 验证是否添加成功
Method sizeMethod = clazz.getMethod("size");
int size = (int) sizeMethod.invoke(instance);
System.out.println("Size of ArrayList after adding element: " + size);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Class.forName("java.util.ArrayList") 获取 ArrayList 类的 Class 对象。clazz.getDeclaredConstructor().newInstance() 创建 ArrayList 的实例。clazz.getMethod("add", Object.class) 获取 ArrayList 类中的 add 方法。addMethod.invoke(instance, "Hello, Reflection!") 调用 add 方法,并传入参数 "Hello, Reflection!"。size 方法验证元素是否成功添加。这段代码展示了如何使用 Java 反射机制动态调用方法。
上一篇:java divide函数
下一篇:java mapstruct
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站