// 反射Java示例代码
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("java.util.ArrayList")获取ArrayList类的Class对象。clazz.getDeclaredConstructor().newInstance()创建ArrayList的一个实例。clazz.getMethod("add", Object.class)获取ArrayList类中的add方法。addMethod.invoke(instance, "Hello Reflection")调用add方法,并传递参数。clazz.getMethods()获取类的所有公共方法,并打印方法名。这段代码展示了如何使用Java反射机制来动态地操作类和方法。
上一篇:java treeset
下一篇:java获取ip地址的方法
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站