一、核心应用场景
- 动态类加载
// 按配置文件加载具体实现类
String className = config.getProperty("service.impl");
Class<?> clazz = Class.forName(className);
Service service = (Service) clazz.getDeclaredConstructor().newInstance();
- 方法信息提取
// 获取带特定注解的方法
Method[] methods = targetClass.getDeclaredMethods();
for (Method method : methods) {
if (method.isAnnotationPresent(Transaction.class)) {
// 处理事务方法
}
}
二、典型实践案例
1. 泛型类型擦除处理
public class TypeResolver {
// 解析字段的泛型参数类型
public static Class<?> resolveFieldType(Field field) {
Type genericType = field.getGenericType();
if (genericType instanceof ParameterizedType) {
return (Class<?>) ((ParameterizedType) genericType)
.getActualTypeArguments()[0];
}
return field.getType();
}
}
2. 动态代理增强
public class LoggingProxy implements InvocationHandler {
private final Object target;
public static Object createProxy(Object target) {
return Proxy.newProxyInstance(
target.getClass().getClassLoader(),
target.getClass().getInterfaces(),
new LoggingProxy(target)
);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("调用方法: " + method.getName());
return method.invoke(target, args);
}
}
三、性能优化实践
// 缓存反射元数据示例
public class MethodCache {
private static final Map<String, Method> cache = new ConcurrentHashMap<>();
public static Method getMethod(Class<?> clazz, String methodName, Class<?>... params)
throws NoSuchMethodException {
String key = clazz.getName() + "#" + methodName;
return cache.computeIfAbsent(key, k -> {
Method method = clazz.getDeclaredMethod(methodName, params);
method.setAccessible(true);
return method;
});
}
}
四、安全实践建议
// 安全的反射调用模式
public class SafeReflection {
public static Object safeInvoke(Object obj, String methodName) {
try {
Method method = obj.getClass().getMethod(methodName);
if (!Modifier.isPublic(method.getModifiers())) {
throw new SecurityException("非公开方法禁止访问");
}
return method.invoke(obj);
} catch (Exception e) {
// 统一异常处理
}
}
}
五、项目级应用示例
简易依赖注入容器
public class SimpleContainer {
private Map<Class<?>, Object> instances = new HashMap<>();
public void register(Class<?> interfaceType, Class<?> implType) {
try {
Constructor<?> constructor = implType.getDeclaredConstructor();
constructor.setAccessible(true);
instances.put(interfaceType, constructor.newInstance());
} catch (Exception e) {
// 异常处理
}
}
public <T> T resolve(Class<T> type) {
return type.cast(instances.get(type));
}
}
注意事项
- 类型安全校验:强制类型转换前务必进行
instanceof
检查 - 访问控制:优先使用
getDeclaredMethod()
+setAccessible(true)
组合 - 异常处理:统一处理
InvocationTargetException
等反射异常 - 资源释放:及时清理反射生成的临时对象
通过合理应用反射机制,可实现灵活的插件架构、动态配置加载等企业级功能。建议结合注解处理器和代码生成技术,在保持灵活性的同时提升运行效率。