Java虚拟机反射机制运行时获取和操作(类、方法、字段)等对象的信息。下面是反射机制的基本使用示例,包括(获取类信息、创建对象、调用方法和访问字段)等操作。
获取类信息: 使用反射可以获取类的信息,如类名、父类、接口、构造函数、方法、字段等。
// 获取类对象
Class<?> clazz = MyClass.class;
// 获取类名
String className = clazz.getName();
// 获取父类
Class<?> superClass = clazz.getSuperclass();
// 获取实现的接口
Class<?>[] interfaces = clazz.getInterfaces();
// 获取构造函数
Constructor<?>[] constructors = clazz.getConstructors();
// 获取方法
Method[] methods = clazz.getMethods();
// 获取字段
Field[] fields = clazz.getDeclaredFields();
创建对象: 使用反射可以在运行时动态创建对象。
Class<?> clazz = MyClass.class;
Object instance = clazz.newInstance();
调用方法: 可以使用反射来调用类的方法。
Class<?> clazz = MyClass.class;
Object instance = clazz.newInstance();
Method method = clazz.getMethod("methodName", parameterType1, parameterType2);
Object result = method.invoke(instance, arg1, arg2);
访问字段: 可以使用反射来访问类的字段。
Class<?> clazz = MyClass.class;
Object instance = clazz.newInstance();
Field field = clazz.getDeclaredField("fieldName");
field.setAccessible(true); // 如果字段是私有的,需要设置为可访问
Object value = field.get(instance);
field.set(instance, newValue);
泛型信息: 反射还允许你获取泛型类型信息。
Method method = MyClass.class.getMethod("someMethod");
Type returnType = method.getGenericReturnType(); // 获取方法返回类型的泛型信息
反射机制是怎么实现解耦的?
动态创建对象: 使用反射,可以在运行时创建对象,而不需要在编译时知道或引用具体的类。这使得你可以根据配置、条件或用户输入等动态选择和创建对象,而不需要硬编码具体的类名。
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
// Shape 接口
public interface Shape {
void draw();
}
// Circle 类
public class Circle implements Shape {
@Override
public void draw() {
System.out.println("Drawing a circle");
}
}
// Rectangle 类
public class Rectangle implements Shape {
@Override
public void draw() {
System.out.println("Drawing a rectangle");
}
}
public class ShapeFactory {
public static Shape createShape(String shapeType) {
try {
// 使用反射获取类对象
Class<?> clazz = Class.forName("com.example." + shapeType); // 假设类在com.example包下
// 获取类的构造函数
Constructor<?> constructor = clazz.getConstructor();
// 使用构造函数创建对象
Object shapeObject = constructor.newInstance();
// 将对象强制转换为Shape接口类型
if (shapeObject instanceof Shape) {
return (Shape) shapeObject;
} else {
throw new IllegalArgumentException("Invalid shape type");
}
} catch (ClassNotFoundException | NoSuchMethodException | InstantiationException |
IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
return null;
}
}
public static void main(String[] args) {
String userInput = "Circle"; // 用户输入的形状类型
Shape shape = createShape(userInput);
if (shape != null) {
shape.draw(); // 调用draw方法
}
}
}
动态加载类: 反射允许你在运行时加载类,从而支持热插拔、插件化和模块化的架构。你可以根据需要加载不同的类或模块,而不必在编译时将它们全部引入。
import java.io.File;
import java.net.URL;
import java.net.URLClassLoader;
public interface Plugin {
void execute();
}
public class PluginLoader {
public static Plugin loadPlugin(String pluginName, String pluginDirectory) throws Exception {
// 构建插件JAR文件的URL
File pluginFile = new File(pluginDirectory + File.separator + pluginName + ".jar");
URL pluginUrl = pluginFile.toURI().toURL();
// 创建自定义类加载器,加载插件类
URLClassLoader classLoader = new URLClassLoader(new URL[] { pluginUrl });
Class<?> pluginClass = classLoader.loadClass(pluginName);
// 实例化插件对象并强制转换为Plugin接口
Object pluginObject = pluginClass.newInstance();
if (pluginObject instanceof Plugin) {
return (Plugin) pluginObject;
} else {
throw new IllegalArgumentException("Invalid plugin class");
}
}
public static void main(String[] args) {
try {
// 加载并执行插件
String pluginName = "SamplePlugin"; // 插件类名
String pluginDirectory = "plugins"; // 插件目录
Plugin plugin = loadPlugin(pluginName, pluginDirectory);
if (plugin != null) {
plugin.execute();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
配置驱动的编程: 反射机制可以用于从外部配置文件、数据库或其他数据源中获取类名、方法名或参数,然后动态加载和执行相应的代码。这种方式将业务逻辑与配置分离,提高了可配置性。
class_name=com.example.MyClass
method_name=doSomething
package com.example;
public class MyClass {
public void doSomething() {
System.out.println("MyClass is doing something.");
}
}
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Properties;
public class ConfigDrivenApp {
public static void main(String[] args) {
try {
// 从配置文件加载配置
Properties properties = new Properties();
FileInputStream fileInputStream = new FileInputStream("config.properties");
properties.load(fileInputStream);
fileInputStream.close();
// 获取类名、方法名和参数
String className = properties.getProperty("class_name");
String methodName = properties.getProperty("method_name");
// 使用反射加载类
Class<?> clazz = Class.forName(className);
Object instance = clazz.newInstance();
// 使用反射获取方法并执行
Method method = clazz.getMethod(methodName);
method.invoke(instance);
} catch (IOException | ClassNotFoundException | NoSuchMethodException |
IllegalAccessException | InstantiationException |
SecurityException | IllegalArgumentException e) {
e.printStackTrace();
}
}
}
Java 的动态代理机制:Java 的动态代理机制会自动将被调用的方法信息(包括方法名称、参数值等)传递给代理对象的 invoke 方法。怎么做到的?
- 首先,定义一个接口 Calculator,其中包含两个方法:add 和 multiply。
public interface Calculator {
int add(int a, int b);
int multiply(int a, int b);
}
- 接下来,创建一个实现了该接口的具体类 CalculatorImpl,它将用于实际的计算。
public class CalculatorImpl implements Calculator {
@Override
public int add(int a, int b) {
return a + b;
}
@Override
public int multiply(int a, int b) {
return a * b;
}
}
- 现在,让我们创建一个动态代理来拦截并处理方法调用。我们将实现一个 InvocationHandler,它的 invoke 方法将接收方法的信息,并在方法调用前后添加日志记录。
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
public class LoggingHandler implements InvocationHandler {
private Calculator target;
public LoggingHandler(Calculator target) {
this.target = target;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// 在方法调用前记录日志
System.out.println("Calling method: " + method.getName() +
" with arguments: " + args[0] + ", " + args[1]);
// 调用被代理对象的方法
Object result = method.invoke(target, args);
// 在方法调用后记录日志
System.out.println("Method " + method.getName() + " returns: " + result);
return result;
}
}
- 现在,我们将创建一个动态代理对象,该代理对象将使用 LoggingHandler 拦截并处理方法调用。
import java.lang.reflect.Proxy;
public class Main {
public static void main(String[] args) {
// 创建被代理对象
Calculator calculator = new CalculatorImpl();
// 创建代理对象
Calculator proxy = (Calculator) Proxy.newProxyInstance(
Calculator.class.getClassLoader(),
new Class<?>[] { Calculator.class },
new LoggingHandler(calculator)
);
// 使用代理对象调用接口方法
int sum = proxy.add(5, 3);
int product = proxy.multiply(4, 7);
}
}
- 在上述示例中,当我们使用代理对象 proxy 调用 add 和 multiply 方法时,Java 的动态代理机制会自动将方法信息传递给 LoggingHandler 类的 invoke 方法。invoke 方法中的 method 参数表示被调用的方法,args 参数表示方法的参数值。
- 动态代理流程:代理类会将接口对象的方法和方法参数通过反射得到,并传递给 InvocationHandler 对象,InvocationHandler 对象,InvocationHandler 对象会聚合被代理对象,并再 invoke 方法中,调用 method.invoke(target, args),实现 被代理对象 方法的调用。