import java.lang.reflect.Method;
public class ReflectionExample {
public static void main(String[] args) {
try {
// 获取Class对象
Class<?> clazz = Class.forName("java.util.ArrayList");
// 获取所有公共方法
Method[] methods = clazz.getMethods();
System.out.println("Public methods in ArrayList:");
for (Method method : methods) {
System.out.println(method.getName());
}
// 获取特定的公共方法(例如:add方法)
Method addMethod = clazz.getMethod("add", Object.class);
System.out.println("Found method: " + addMethod.getName());
// 创建ArrayList实例
Object arrayListInstance = clazz.getDeclaredConstructor().newInstance();
// 调用add方法
addMethod.invoke(arrayListInstance, "Hello, Reflection!");
} catch (Exception e) {
e.printStackTrace();
}
}
}
Class.forName("java.util.ArrayList")
来获取ArrayList
类的Class
对象。clazz.getMethods()
获取ArrayList
类的所有公共方法,并打印方法名。clazz.getMethod("add", Object.class)
获取ArrayList
类中的add
方法。clazz.getDeclaredConstructor().newInstance()
创建ArrayList
的一个实例。addMethod.invoke(arrayListInstance, "Hello, Reflection!")
调用ArrayList
实例的add
方法,添加一个字符串。这个示例展示了如何使用Java反射机制来获取类的信息、创建实例以及调用方法。
上一篇:java基础数据类型有几种
下一篇:java.lang.object
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站