导入
反射基础
学习如何使用反射 API 在运行时动态地检查和操作 Java 类、方法和字段,同时理解其应用场景和权衡。
1public class ClassEntryPoint { 2 public static void main(String[] args) throws ClassNotFoundException { 3 // 1. 使用 .class 字面量 4 Class<String> stringClass = String.class; 5 System.out.println("From literal: " + stringClass.getName()); 6 7 // 2. 在实例上调用 getClass() 8 String greeting = "Hello Reflection"; 9 Class<? extends String> instanceClass = greeting.getClass(); 10 System.out.println("From instance: " + instanceClass.getName()); 11 12 // 3. 使用 Class.forName() 通过字符串名称 13 // 可能抛出 ClassNotFoundException 14 Class<?> dynamicClass = Class.forName("java.lang.String"); 15 System.out.println("From string name: " + dynamicClass.getName()); 16 17 // 验证它们是否是同一个对象 18 System.out.println("Are they equal? " + (stringClass == dynamicClass)); 19 } 20}
1import java.lang.reflect.Constructor; 2 3class Robot { 4 private String name; 5 6 public Robot(String name) { 7 this.name = name; 8 } 9 10 @Override 11 public String toString() { 12 return "Robot[name=" + name + "]"; 13 } 14} 15 16public class InstanceCreation { 17 public static void main(String[] args) throws Exception { 18 // 获取 Class 对象 19 Class robotClass = Robot.class; 20 21 // 查找接受单个 String 参数的构造函数 22 Constructor constructor = robotClass.getConstructor(String.class); 23 24 // 通过传递参数创建新实例 25 Object myRobot = constructor.newInstance("R2-D2"); 26 27 System.out.println(myRobot); 28 } 29}
1import java.lang.reflect.Method; 2 3class Robot { 4 public int compute(int a, int b) { 5 return a + b; 6 } 7} 8 9public class MethodInvocation { 10 public static void main(String[] args) throws Exception { 11 Robot bot = new Robot(); 12 Class clazz = bot.getClass(); 13 14 // 获取接受两个 int.class 参数的 "compute" 方法 15 Method computeMethod = clazz.getMethod("compute", int.class, int.class); 16 17 // 在 'bot' 实例上调用该方法 18 // 等价于:int result = bot.compute(10, 20); 19 Object result = computeMethod.invoke(bot, 10, 20); 20 21 System.out.println("Result: " + result); 22 } 23}
1import java.lang.reflect.Field; 2 3class Robot { 4 private String secretCode = "9999"; // 私有字段 5 6 public void verify() { 7 System.out.println("Current Code: " + secretCode); 8 } 9} 10 11public class FieldAccess { 12 public static void main(String[] args) throws Exception { 13 Robot bot = new Robot(); 14 Class clazz = bot.getClass(); 15 16 // 1. 获取类中声明的私有字段 17 Field codeField = clazz.getDeclaredField("secretCode"); 18 19 // 2. 绕过访问控制检查 20 codeField.setAccessible(true); 21 22 // 3. 读取值 23 System.out.println("Original value: " + codeField.get(bot)); 24 25 // 4. 修改值 26 codeField.set(bot, "1234"); 27 28 bot.verify(); 29 } 30}