package com.example;
import java.lang.reflect.*;
class Person {
private String name;
private int age;
public Person() {
this.name = "Unknown";
this.age = 0;
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public void introduce() {
System.out.println("Hi, I'm " + name + " and I'm " + age + " years old.");
}
public void introduce(String greeting, boolean formal) {
if (formal) {
System.out.println(greeting + ", I am " + name + " and I am " + age + " years old.");
} else {
System.out.println(greeting + "! " + name + " here, " + age + " years old.");
}
}
private void secretMethod() {
System.out.println("This is a secret method!");
}
}
public class ReflectionDemo {
public static void main(String[] args) {
try {
// 1. 获取类信息
Class<?> personClass = Class.forName("com.example.Person");
System.out.println("Class name: " + personClass.getName());
// 使用 .class
Class<?> personClass2 = Person.class;
System.out.println("Simple name: " + personClass2.getSimpleName());
// 使用对象的 getClass()
Person person = new Person();
Class<?> personClass3 = person.getClass();
System.out.println("Package name: " + personClass3.getPackage().getName());
// 2. 创建实例
// 使用 newInstance() 调用无参构造函数
Person person1 = (Person) personClass.newInstance();
System.out.println("\nCreated instance using newInstance():");
person1.introduce();
// 使用 Constructor 调用带参数构造函数
Constructor<?> constructor = personClass.getConstructor(String.class, int.class);
Person person2 = (Person) constructor.newInstance("Alice", 30);
System.out.println("\nCreated instance using constructor:");
person2.introduce();
// 3. 方法操作
// 获取并调用无参的 introduce 方法
Method introduceMethod = personClass.getMethod("introduce");
System.out.println("\nInvoking introduce method without parameters:");
introduceMethod.invoke(person2);
// 获取并调用带参数的 introduce 方法
Method parameterizedIntroduceMethod = personClass.getMethod("introduce", String.class, boolean.class);
System.out.println("\nInvoking introduce method with parameters:");
parameterizedIntroduceMethod.invoke(person2, "Hello", true);
parameterizedIntroduceMethod.invoke(person2, "Hey", false);
// 获取所有公共方法
System.out.println("\nAll public methods:");
Method[] methods = personClass.getMethods();
for (Method method : methods) {
System.out.println(method.getName() + " - Parameters: " + method.getParameterCount());
}
// 获取所有声明的方法(包括私有方法)
System.out.println("\nAll declared methods:");
Method[] declaredMethods = personClass.getDeclaredMethods();
for (Method method : declaredMethods) {
System.out.println(method.getName());
}
// 获取并调用私有方法
Method secretMethod = personClass.getDeclaredMethod("secretMethod");
secretMethod.setAccessible(true);
System.out.println("\nInvoking private method:");
secretMethod.invoke(person2);
// 4. 字段操作
// 获取所有公共字段
System.out.println("\nAll public fields:");
Field[] fields = personClass.getFields();
for (Field field : fields) {
System.out.println(field.getName());
}
// 获取所有声明的字段(包括私有字段)
System.out.println("\nAll declared fields:");
Field[] declaredFields = personClass.getDeclaredFields();
for (Field field : declaredFields) {
System.out.println(field.getName());
}
// 获取并修改特定字段
Field nameField = personClass.getDeclaredField("name");
nameField.setAccessible(true);
System.out.println("\nChanging private field value:");
nameField.set(person2, "Bob");
person2.introduce();
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException |
NoSuchMethodException | InvocationTargetException | NoSuchFieldException e) {
e.printStackTrace();
}
}
}
Java反射
获取类信息
Class对象
- Class.forName(“类名”)
- 类名.class
- 对象.getClass()
例子
- Class<?> cls = Class.forName(“com.example.MyClass”);
创建实例
newInstance()
- 调用无参构造函数
- 例: MyClass obj = (MyClass) cls.newInstance();
Constructor
- 获取指定构造函数
- 调用带参数构造函数
- personClass.getConstructor(String.class, int.class);
- 例: Constructor<?> con = cls.getConstructor(String.class); MyClass obj = (MyClass) con.newInstance(“参数”);
方法操作
getMethods()
- 获取所有公共方法
- 包括继承的方法
getDeclaredMethods()
- 获取所有声明的方法
- 包括私有方法
getMethod(String name, Class<?>… parameterTypes)
- 获取特定方法
- Method method = someClass.getMethod(“myMethod”, String.class, int.class);
invoke(Object obj, Object… args)
- 调用方法
- 例: Method method = cls.getMethod(“methodName”, String.class); method.invoke(obj, “参数”);
字段操作
getFields()
- 获取所有公共字段
getDeclaredFields()
- 获取所有声明的字段
getField(String name)
- 获取特定字段
set(Object obj, Object value)
- 设置字段值
- 例: Field field = cls.getDeclaredField(“fieldName”); field.setAccessible(true); field.set(obj, value);
注意事项
性能开销
- 反射操作较慢
安全考虑
- 可能破坏封装
异常处理
- 需要处理反射相关异常
这个思维导图提供了Java反射的主要概念和操作的概览。它涵盖了获取类信息、创建实例、方法操作、字段操作以及使用反射时需要注意的事项。
完整的代码示例展示了如何在实际应用中使用这些反射概念,包括如何获取类信息、创建实例、调用方法(包括带参数的方法和私有方法)以及操作字段。
这两部分结合起来,为Java反射提供了全面的理论和实践指南。如果您需要进一步的解释或者对特定部分有疑问,请随时告诉我。