Java动态代理

Java提供了动态代理,可以完成AOP和装饰模式的功能,主要的Proxy类和InvocationHandler接口:
1、Proxy类
[code]
public class Proxy implements java.io.Serializable {
//...
public static Class getProxyClass( ClassLoader loader,
Class[] interfaces )throws IllegalArgumentException;

public static Object newProxyInstance( ClassLoader loader,
Class[] interfaces,InvocationHandler h )throws IllegalArgumentException;
public static boolean isProxyClass( Class cl );
public static InvocationHandler getInvocationHandler( Object proxy )
throws IllegalArgumentException;
}
[/code]
Proxy类提供了一些工具方法:
getProxyClass得到代理类,如果不存在则动态创建。
newProxyInstance创建一个代理实例。
isProxyClass判断是否是一个代理类。
getInvocationHandler得到InvocationHandler。
一般先调用isProxyClass,判断是,然后再使用getInvocationHandler
参数:loader,创建对象需要classLoader,创建proxy也需要,一般被代理
真实对象得到:realObj.getClass().getClassLoader();
interfaces,代理和真实对象实现的接口。
创建一个代理一般使用以下两种方式:
方法一:
[code]
Proxy cl = getProxyClass( SomeInterface.getClassLoader(),
Class[]{SomeInterface.class} );
Constructor cons = cl.getConstructor( new Class[]{InvocationHandler.class} );
Object proxy = cons.newInstance( new Object[] { new SomeIH( obj ) } );
[/code]
方法二:
[code]
Object proxy = Proxy.newProxyInstance( SomeInterface.getClassLoader(),
Class[]{SomeInterface.class},
new SomeIH( obj ) );
[/code]
2、InvocationHandler接口:
[code]
public interface InvocationHandler {
public Object invoke( Object proxy, Method method, Object[] args )
throws Throwable;
}
[/code]
代理对象通过这个接口来将真实的对象联系起来。过程是:
代理对象直接调用InvocationHandler 的invoke方法,把自己作为proxy参数,调用的函数
作为method参数,调用函数的参数作为args传递过来,我们只需要在invoke方法中做一些事情,然后再调用被代理对象的方法就可以了。
我们以一个例子说明:
跟踪函数的调用过程:
函数执行之前和之后打印出跟踪信息:
实现InvocationHandler接口:
[code]
import java.io.PrintWriter;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;


public class MethodTracker implements InvocationHandler{;
private Object target;
private PrintWriter out;

private MethodTracker(Object obj, PrintWriter out){
this.target = obj;
this.out = out;
}

public static Object createProxy(Object obj, PrintWriter out){
return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(), new MethodTracker(obj,out));
}
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
Object result = null;
try{
out.println(method.getName() + "(...) called");
result = method.invoke(target, args);
}catch(InvocationTargetException e){
out.println(method.getName() + " throws " + e.getCause());
throw e.getCause();
}
out.println(method.getName() + " returns");
return result;
}

}
[/code]
我们测试一下:
[code]
import java.io.PrintWriter;

interface IHelloWorld{
void hello();
}

class HelloWorld implements IHelloWorld{
private String name = "world";

public void hello(){
System.out.println("Hello," + name);
}

public void setName(String name){
this.name = name;
}
}

public class TestTracker {
public static void main(String[] args) {
IHelloWorld tc = (IHelloWorld) MethodTracker.createProxy(new HelloWorld(),new PrintWriter(System.out,true));
tc.hello();
}
}
[/code]
Java动态代理的缺点是只能对接口进行代理,无法代理class。
3.高级进阶:
如果我们想象拦截器那样一层一层的拦截,也就是形成一个代理链,上面的实现可能会出现问题,比如我们想有个同步调用方法的代理,如果按照上面的实现
IHelloWorld tc = (IHelloWorld) MethodSynchronizer.createProxy(
MethodTracker.createProxy(new HelloWorld(),new PrintWriter(System.out,true))
);
将是错误的,因为他使用的同步对象是内层代理,而不是真实要被代理的对象。
要完成上面的功能,我们可以通过下面实现来达到:
[code]
import java.lang.reflect.Field;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;

public abstract class InvocationHandlerBase implements InvocationHandler{
protected Object nextTarget;
protected Object realTarget = null;

public InvocationHandlerBase(Object target){
nextTarget = target;
if(nextTarget != null){
realTarget = findRealTarget(nextTarget);
if(realTarget == null){
throw new RuntimeException("findRealTarget failure");
}
}
}

protected final Object getRealTarget(){
return realTarget;
}

protected static final Object findRealTarget(Object t){
if(! Proxy.isProxyClass(t.getClass()))
return t;
InvocationHandler ih = Proxy.getInvocationHandler(t);
if(InvocationHandlerBase.class.isInstance(ih)){
return ((InvocationHandlerBase)ih).getRealTarget();
}else{
try{
Field f = findField(ih.getClass(), "target");
if(Object.class.isAssignableFrom(f.getType())&&
! f.getType().isArray()){
f.setAccessible(true);
Object innerTarget = f.get(ih);
return findRealTarget(innerTarget);
}
return null;
}catch(Exception e){
return null;
}
}
}

public static Field findField(Class<?> cls, String name) throws NoSuchFieldException{
if(cls != null){
try{
return cls.getDeclaredField(name);
}catch(NoSuchFieldException e){
return findField(cls.getSuperclass(),name);
}
}else{
throw new NoSuchFieldException();
}
}
}

[/code]
注意,这里我们约定了实现InvocationHandler接口的类使用target字段来保存被代理的对象,通过继承InvocationHandlerBase便可以达到所说的效果:
[code]
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;


public class MethodSynchronizer extends InvocationHandlerBase{
public static Object createProxy(Object obj){
return Proxy.newProxyInstance(obj.getClass().getClassLoader(),
obj.getClass().getInterfaces(), new MethodSynchronizer(obj));
}
private MethodSynchronizer(Object obj){
super(obj);
}

@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {

Object result = null;
synchronized( this.getRealTarget() ){
result = method.invoke(nextTarget, args);
}
return result;
}
}
[/code]
测试代码:
[code]
import java.io.PrintWriter;

interface IHelloWorld{
void hello();
}

class HelloWorld implements IHelloWorld{
private String name = "world";

public void hello(){
System.out.println("Hello," + name);
}

public void setName(String name){
this.name = name;
}
}

public class TestTracker {
public static void main(String[] args) {
IHelloWorld tc = (IHelloWorld) MethodSynchronizer.createProxy(
MethodTracker.createProxy(new HelloWorld(),new PrintWriter(System.out,true))
);
tc.hello();
}
}
[/code]
### Java 动态代理的实现原理与用法 #### 1. Java 动态代理概述 Java 动态代理是一种在运行时动态生成代理对象的技术,它允许开发者无需提前定义具体的代理类即可完成方法拦截和增强功能。这种机制广泛应用于 AOP(面向切面编程)、事务管理以及日志记录等领域[^2]。 #### 2. 动态代理的核心组件 动态代理主要依赖于 `java.lang.reflect.Proxy` 类和 `InvocationHandler` 接口来实现。以下是其核心组成部分: - **Proxy 类**: 提供了用于创建动态代理实例的方法。 - **InvocationHandler 接口**: 定义了一个处理方法调用的回调接口,通过该接口可以自定义代理行为。 当客户端调用代理对象上的某个方法时,实际执行的是由 InvocationHandler 处理逻辑所指定的操作[^3]。 #### 3. JDK 原生动态代理实现 JDK 动态代理基于反射技术,在运行期间为一组接口动态生成代理类及其实例。具体流程如下: - 创建一个实现了 `InvocationHandler` 接口的对象。 - 使用 `Proxy.newProxyInstance()` 方法传入目标类加载器、目标类实现的一组接口列表以及上述 handler 对象,从而获得代理实例。 下面是一个简单的示例代码展示如何利用 JDK 动态代理实现基本的日志打印功能: ```java import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; // 定义服务接口 interface GreetingService { void sayHello(String name); } // 实现服务接口的具体业务逻辑 class SimpleGreetingServiceImpl implements GreetingService { @Override public void sayHello(String name) { System.out.println("Hello, " + name); } } // 自定义 InvocationHandler 来拦截并扩展方法调用 class LoggingInvocationHandler implements InvocationHandler { private Object target; // 被代理的目标对象 public LoggingInvocationHandler(Object target) { this.target = target; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("[Before] Executing: " + method.getName()); // 执行原始方法 Object result = method.invoke(target, args); System.out.println("[After] Finished execution."); return result; } } public class JdkDynamicProxyDemo { public static void main(String[] args) { // 初始化真实的服务实现 GreetingService greetingService = new SimpleGreetingServiceImpl(); // 构建带有日志功能的代理对象 GreetingService proxyInstance = (GreetingService) Proxy.newProxyInstance( greetingService.getClass().getClassLoader(), greetingService.getClass().getInterfaces(), new LoggingInvocationHandler(greetingService)); // 测试代理效果 proxyInstance.sayHello("World"); } } ``` 此程序展示了如何通过动态代理增加额外的功能而不修改原有代码结构[^1]。 #### 4. CGLib 动态代理实现 除了 JDK 内置支持外,还可以借助第三方库如 CGLib 进行动态代理操作。CGLib 主要针对那些未继承任何接口或者希望直接操控实体类场景下更为适用。它的内部工作机理涉及字节码层面操作,能够子类化任意非 final 的普通类,并重写其中的方法达到相同目的。 需要注意的是,由于两者设计初衷不同,在性能表现上可能会有所差异;通常情况下,如果仅需对接口做封装,则推荐优先考虑更轻量级也更加直观易懂的 JDK 方案。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值