理解Java的动态代理机制示例
Java的动态代理主要通过Proxy类和InvocationHandler接口来实现。下面是一个简单的示例:
- 创建接口(需要定义方法)
public interface MyInterface {
void myMethod();
}
- 创建一个实现了接口且作为代理的对象
// 实现MyInterface接口
class MyImplementation implements MyInterface {
@Override
public void myMethod() {
System.out.println("Method called in proxy");
}
}
// 作为动态代理的实现类
class MyInvocationHandler implements InvocationHandler {
private MyImplementation implementation;
public MyInvocationHandler(MyImplementation implementation) {
this.implementation = implementation;
}
@Override
public Object invoke(Object obj, Method method, Object[] args) {
System.out.println("Before proxy call");
// 调用方法,注意这里已经改变了obj的实际引用
Object result = method.invoke(implementation, args);
System.out.println("After proxy call");
return result;
}
}
- 使用代理对象
// 创建动态代理对象和处理者
MyImplementation implementation = new MyImplementation();
MyInvocationHandler handler = new MyInvocationHandler(implementation);
// 创建Proxy对象并使用它
Object proxyObj = Proxy.newProxyInstance(
ClassLoader.getSystemClassLoader(),
new Class[]{MyInterface.class}, // 需要代理的接口列表
handler // 处理器,即动态代理的核心部分
);
现在,通过这个动态代理,你可以调用真实对象的方法,同时在方法调用前后进行额外的操作。
还没有评论,来说两句吧...