我来为您详细介绍Java反射调用的统一流程,并提供完整的示例代码。

Java反射调用统一流程
核心流程步骤
graph TD
A[获取Class对象] --> B[获取构造方法]
B --> C[创建实例]
C --> D[获取成员变量/方法]
D --> E[设置访问权限]
E --> F[调用/操作]
F --> G[处理结果]
完整实现代码
import java.lang.reflect.*;
import java.util.Arrays;
/**
* Java反射调用统一流程示例
*/
public class ReflectionDemo {
// 示例类
static class User {
private String name;
private int age;
// 无参构造
public User() {
this.name = "default";
this.age = 0;
}
// 有参构造
public User(String name, int age) {
this.name = name;
this.age = age;
}
// 私有方法
private String getInfo() {
return String.format("User{name='%s', age=%d}", name, age);
}
// 公共方法
public void setName(String name) {
this.name = name;
}
public void display() {
System.out.println("Name: " + name + ", Age: " + age);
}
@Override
public String toString() {
return "User{" + "name='" + name + '\'' + ", age=" + age + '}';
}
}
/**
* 统一的反射调用流程
*/
public static class ReflectionInvoker {
/**
* 1. 获取Class对象
*/
public static Class<?> getClass(String className) throws ClassNotFoundException {
return Class.forName(className);
}
/**
* 2. 获取构造方法并创建实例
*/
public static Object createInstance(Class<?> clazz, Object... args)
throws Exception {
// 获取构造方法
Constructor<?> constructor = getConstructor(clazz, args);
// 设置可访问(用于私有构造方法)
constructor.setAccessible(true);
// 创建实例
return constructor.newInstance(args);
}
/**
* 获取匹配的构造方法
*/
private static Constructor<?> getConstructor(Class<?> clazz, Object... args)
throws NoSuchMethodException {
if (args == null || args.length == 0) {
return clazz.getDeclaredConstructor();
}
// 获取参数类型
Class<?>[] paramTypes = getParameterTypes(args);
return clazz.getDeclaredConstructor(paramTypes);
}
/**
* 3. 获取方法并调用
*/
public static Object invokeMethod(Object instance, String methodName,
Object... args) throws Exception {
// 获取方法对象
Method method = getMethod(instance.getClass(), methodName, args);
// 设置可访问(用于私有方法)
method.setAccessible(true);
// 调用方法
return method.invoke(instance, args);
}
/**
* 获取匹配的方法
*/
private static Method getMethod(Class<?> clazz, String methodName,
Object... args) throws NoSuchMethodException {
if (args == null || args.length == 0) {
return clazz.getDeclaredMethod(methodName);
}
// 获取参数类型
Class<?>[] paramTypes = getParameterTypes(args);
return clazz.getDeclaredMethod(methodName, paramTypes);
}
/**
* 4. 访问成员变量
*/
public static Object getFieldValue(Object instance, String fieldName)
throws Exception {
Field field = instance.getClass().getDeclaredField(fieldName);
field.setAccessible(true);
return field.get(instance);
}
/**
* 5. 设置成员变量
*/
public static void setFieldValue(Object instance, String fieldName,
Object value) throws Exception {
Field field = instance.getClass().getDeclaredField(fieldName);
field.setAccessible(true);
field.set(instance, value);
}
/**
* 获取参数类型数组
*/
private static Class<?>[] getParameterTypes(Object... args) {
return Arrays.stream(args)
.map(Object::getClass)
.toArray(Class<?>[]::new);
}
/**
* 完整示例:展示统一调用流程
*/
public static void demonstrateFullFlow() throws Exception {
System.out.println("=== 反射调用统一流程示例 ===");
// 步骤1: 获取Class对象
System.out.println("\n1. 获取Class对象");
Class<?> userClass = getClass("ReflectionDemo$User");
System.out.println(" Class: " + userClass.getName());
// 步骤2: 创建实例
System.out.println("\n2. 创建实例");
Object user1 = createInstance(userClass, "张三", 25);
Object user2 = createInstance(userClass);
System.out.println(" User1: " + user1);
System.out.println(" User2: " + user2);
// 步骤3: 调用方法
System.out.println("\n3. 调用方法");
System.out.println(" 调用公共方法setName:");
invokeMethod(user2, "setName", "李四");
System.out.println(" 调用私有方法getInfo:");
Object info = invokeMethod(user2, "getInfo");
System.out.println(" Private method result: " + info);
// 步骤4: 访问成员变量
System.out.println("\n4. 访问成员变量");
String name1 = (String) getFieldValue(user1, "name");
int age1 = (int) getFieldValue(user1, "age");
System.out.println(" User1 name: " + name1);
System.out.println(" User1 age: " + age1);
// 步骤5: 设置成员变量
System.out.println("\n5. 设置成员变量");
setFieldValue(user1, "name", "王五");
setFieldValue(user1, "age", 30);
System.out.println(" Modified User1: " + user1);
// 综合调用
System.out.println("\n6. 综合调用示例");
System.out.println(" User1 name (after set): " + getFieldValue(user1, "name"));
invokeMethod(user1, "display");
}
}
/**
* 高级反射调用 - 缓存优化版本
*/
public static class ReflectionCache {
private static final java.util.Map<String, Constructor<?>> CONSTRUCTOR_CACHE =
new java.util.concurrent.ConcurrentHashMap<>();
private static final java.util.Map<String, Method> METHOD_CACHE =
new java.util.concurrent.ConcurrentHashMap<>();
private static final java.util.Map<String, Field> FIELD_CACHE =
new java.util.concurrent.ConcurrentHashMap<>();
private static String getConstructorKey(Class<?> clazz, Class<?>... paramTypes) {
return clazz.getName() + ":" + Arrays.toString(paramTypes);
}
private static String getMethodKey(Class<?> clazz, String methodName, Class<?>... paramTypes) {
return clazz.getName() + "." + methodName + ":" + Arrays.toString(paramTypes);
}
private static String getFieldKey(Class<?> clazz, String fieldName) {
return clazz.getName() + "." + fieldName;
}
public static Object createInstanceCached(Class<?> clazz, Object... args)
throws Exception {
Class<?>[] paramTypes = args.length == 0 ? new Class<?>[0] :
Arrays.stream(args).map(Object::getClass).toArray(Class<?>[]::new);
String key = getConstructorKey(clazz, paramTypes);
Constructor<?> constructor = CONSTRUCTOR_CACHE.computeIfAbsent(key, k -> {
try {
return clazz.getDeclaredConstructor(paramTypes);
} catch (Exception e) {
throw new RuntimeException(e);
}
});
constructor.setAccessible(true);
return constructor.newInstance(args);
}
public static Object invokeMethodCached(Object instance, String methodName,
Object... args) throws Exception {
Class<?> clazz = instance.getClass();
Class<?>[] paramTypes = args.length == 0 ? new Class<?>[0] :
Arrays.stream(args).map(Object::getClass).toArray(Class<?>[]::new);
String key = getMethodKey(clazz, methodName, paramTypes);
Method method = METHOD_CACHE.computeIfAbsent(key, k -> {
try {
return clazz.getDeclaredMethod(methodName, paramTypes);
} catch (Exception e) {
throw new RuntimeException(e);
}
});
method.setAccessible(true);
return method.invoke(instance, args);
}
}
public static void main(String[] args) {
try {
// 基础反射调用
ReflectionInvoker.demonstrateFullFlow();
// 缓存版本示例
System.out.println("\n=== 缓存版本反射调用 ===");
Class<?> userClass = ReflectionInvoker.getClass("ReflectionDemo$User");
Object user = ReflectionCache.createInstanceCached(userClass, "测试", 20);
System.out.println(" Created: " + user);
Object name = ReflectionCache.invokeMethodCached(user, "getInfo");
System.out.println(" Got info: " + name);
} catch (Exception e) {
e.printStackTrace();
}
}
}
反射调用性能优化建议
/**
* 性能优化示例
*/
public class ReflectionOptimizer {
// 1. 缓存反射对象
private static final java.util.Map<String, Method> methodCache =
new java.util.concurrent.ConcurrentHashMap<>();
// 2. 使用MethodHandles提高性能
public static Object invokeWithMethodHandles(Object obj, String methodName,
Object... args) throws Throwable {
MethodHandles.Lookup lookup = MethodHandles.lookup();
MethodType methodType = MethodType.methodType(Object.class,
Arrays.stream(args).map(Object::getClass).toArray(Class<?>[]::new));
MethodHandle methodHandle = lookup.findVirtual(obj.getClass(), methodName, methodType);
return methodHandle.invokeWithArguments(obj, args);
}
// 3. 批量操作
public static void batchReflection() throws Exception {
Class<?> clazz = Class.forName("com.example.User");
// 一次性获取所有字段
Field[] fields = clazz.getDeclaredFields();
AccessibleObject.setAccessible(fields, true);
// 批量处理
Object instance = clazz.getDeclaredConstructor().newInstance();
for (Field field : fields) {
System.out.println(field.getName() + ": " + field.get(instance));
}
}
}
异常处理最佳实践
/**
* 反射异常处理
*/
public class ReflectionExceptionHandler {
public static <T> T safeReflectiveCall(Class<T> clazz, String methodName,
Object instance, Object... args) {
try {
Method method = clazz.getDeclaredMethod(methodName,
getParameterTypes(args));
method.setAccessible(true);
return (T) method.invoke(instance, args);
} catch (NoSuchMethodException e) {
throw new RuntimeException("Method not found: " + methodName, e);
} catch (IllegalAccessException e) {
throw new RuntimeException("Method not accessible: " + methodName, e);
} catch (InvocationTargetException e) {
throw new RuntimeException("Method threw exception: " + methodName,
e.getTargetException());
} catch (Exception e) {
throw new RuntimeException("Unexpected reflection error", e);
}
}
}
这个统一流程涵盖了Java反射调用的所有关键步骤,并提供了最佳实践和性能优化建议。