代码分析:
package com.jd.test;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import com.jd.calculator.CalculatorService;
import com.jd.calculator.ICalculatorService;
public class Test {
//动态(程序运行时实现和目标类相同接口的java类)代理()
CalculatorService calculatorService;
public Test(CalculatorService calculatorService) {
this.calculatorService = calculatorService;
}
InvocationHandler h = new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println(proxy.getClass().getName());
System.out.println(method.getDeclaringClass().getName());
String name = method.getName();
System.out.println(this.getClass().getName()+":The "+name+" method begins.");
System.out.println(this.getClass().getName()+":Parameters of the "+name+" method: ["+args[0]+","+args[1]+"]");
Object result = method.invoke(calculatorService, args);//目标方法
System.out.println(this.getClass().getName()+":Result of the "+name+" method:"+result);
System.out.println(this.getClass().getName()+":The "+name+" method ends.");
return result;
}
};
public Object get() {
return Proxy.newProxyInstance(Test.class.getClassLoader(), new Class[] {ICalculatorService.class}, h);//产生一个动态class类,并返回一个动态对象
}
public static void main(String[] args) {
System.getProperties().put("sun.misc.ProxyGenerator.saveGeneratedFiles", "true");
Test test = new Test(new CalculatorService());
ICalculatorService calculatorService = (ICalculatorService) test.get();//获取代理对象
System.out.println(calculatorService.getClass().getName());
int result = calculatorService.add(1, 1);
System.out.println("-->"+result);
}
}
前提:
CalculatorService中有加减乘除四个方法,分别是public int add(int a, int b),public int sub(int a, int b),
public int mul(int a, int b),public int div(int a, int b),
CalculatorService实现ICalculatorService接口
main方法:(先大致说明每一步执行后得到的结果,下面再进行详细解释)
第一行:生成代理类形成的class文件
第二行:为上面声明的calculatorService赋值
第三行:执行Test中的get()方法,产生一个动态代理类(下面简称代理类),并且返回一个动态类的动态对象
第四行:(这行是为了验证,后面说明)
第五行:获得执行add方法后的结果
第六行:输出结果
各行结果解释:
第一行: JDK动态代理生成class文件:
System.getProperties().put("sun.misc.ProxyGenerator.saveGeneratedFiles", "true");
CGLib生成class文件:
System.setProperty(DebuggingClassWriter.DEBUG_LOCATION_PROPERTY, "E://tmp");
第二行:这个很容易理解,调用了Test类的有参构造方法Test(CalculatorService calculatorService),为calculatorService赋值
第三行:调用了无参方法get(),该方法中又调用了newProxyInstance()方法,第一个参数中的getClassLoader()方法返回一个ClassLoader类型的变量,第二个参数是接口的class对象,第三个参数是InvocationHandler匿名内部类对象,进入newProxyInstance()方法有以下代码;
public static Object newProxyInstance(ClassLoader loader,
Class<?>[] interfaces,
InvocationHandler h)
throws IllegalArgumentException
{
Objects.requireNonNull(h);
final Class<?>[] intfs = interfaces.clone();
final SecurityManager sm = System.getSecurityManager();
if (sm != null) {
checkProxyAccess(Reflection.getCallerClass(), loader, intfs);
}
/*
* Look up or generate the designated proxy class.
*/
Class<?> cl = getProxyClass0(loader, intfs);
/*
* Invoke its constructor with the designated invocation handler.
*/
try {
if (sm != null) {
checkNewProxyPermission(Reflection.getCallerClass(), cl);
}
final Constructor<?> cons = cl.getConstructor(constructorParams);
final InvocationHandler ih = h;
if (!Modifier.isPublic(cl.getModifiers())) {
AccessController.doPrivileged(new PrivilegedAction<Void>() {
public Void run() {
cons.setAccessible(true);
return null;
}
});
}
return cons.newInstance(new Object[]{h});
} catch (IllegalAccessException|InstantiationException e) {
throw new InternalError(e.toString(), e);
} catch (InvocationTargetException e) {
Throwable t = e.getCause();
if (t instanceof RuntimeException) {
throw (RuntimeException) t;
} else {
throw new InternalError(t.toString(), t);
}
} catch (NoSuchMethodException e) {
throw new InternalError(e.toString(), e);
}
}
在这个方法中,有几个地方需要明白:
①:final Class<?>[] intfs = interfaces.clone(); clone()拷贝一个interfaces对象,即向newProxyInstance()传入的ICalculatorService的class对象
②:Class<?> cl = getProxyClass0(loader, intfs); 生成指定接口ICalculatorService的代理类,并获得代理类的class对象;(另外,在getProxyClass0(loader, intfs)方法里,JDK对代理进行了缓存,如果已经存在相应的代理类,直接返回,否则才会通过ProxyClassFactory来创建代理)
③:final Constructor<?> cons = cl.getConstructor(constructorParams); 获取代理类cl的构造方法,constructorParams类型是对象数组。
④:return cons.newInstance(new Object[]{h}); 创建一个代理类对象并返回,并且调用其中的有参构造方法$Proxy0(InvocationHandler invocationhandler),参数h为传入的InvocationHandler匿名内部类对象
在这有一点需要说明,通过反编译器,可以得到编译后的java代码表示的class文件,下面是为了容易理解,删去部分代码后得到的:
package com.sun.proxy;
import com.jd.calculator.ICalculatorService;
import java.lang.reflect.*;
public final class $Proxy0 extends Proxy
implements ICalculatorService
{
public $Proxy0(InvocationHandler invocationhandler)
{
super(invocationhandler);
}
public final int add(int i, int j)
{
try
{
return (
(Integer)super.h.invoke(this, m3, new Object[] {Integer.valueOf(i), Integer.valueOf(j)
).intValue();
}
catch(Exception(throwable);
}
}
private static Method m3;
static
{
m3 = Class.forName("com.jd.calculator.ICalculatorService").getMethod("add", new Class[] {Integer.TYPE, Integer.TYPE});
}
}
④中执行的有参构造方法,就是这个类中的有参构造方法;这个构造方法为父类Proxy中的h赋值,这一步执行完毕之后,Test中main方法中的第三行代码执行完毕,得到了一个代理对象
protected InvocationHandler h;
/**
* Prohibits instantiation.
*/
private Proxy() {
}
/**
* Constructs a new {@code Proxy} instance from a subclass
* (typically, a dynamic proxy class) with the specified value
* for its invocation handler.
*
* @param h the invocation handler for this proxy instance
*
* @throws NullPointerException if the given invocation handler, {@code h},
* is {@code null}.
*/
protected Proxy(InvocationHandler h) {
Objects.requireNonNull(h);
this.h = h;
}
第四行:这一步是为了验证,得到的代理对象和上面invoke()中传入的proxy,是相同的
第五行:calculatorService的值是代理对象,所以执行代理类中的add方法,
package com.sun.proxy;
import com.jd.calculator.ICalculatorService;
import java.lang.reflect.*;
public final class $Proxy0 extends Proxy
implements ICalculatorService
{
public $Proxy0(InvocationHandler invocationhandler)
{
super(invocationhandler);
}
public final int add(int i, int j)
{
try
{
return (
(Integer)super.h.invoke(this, m3, new Object[] {Integer.valueOf(i), Integer.valueOf(j)
).intValue();
}
catch(Exception(throwable);
}
}
private static Method m3;
static
{
m3 = Class.forName("com.jd.calculator.ICalculatorService").getMethod("add", new Class[] {Integer.TYPE, Integer.TYPE});
}
}
add方法中(Integer)super.h.invoke(this, m3, new Object[] {Integer.valueOf(i), Integer.valueOf(j)
由于上面④中调用有参构造方法$Proxy0(InvocationHandler invocationhandler),给这个类的父类Proxy中的invocationHandler赋的值为invocationHandler对象,所以在这里super.h是invocationHandler , super.h.invoke相当于invocationHandler.invoke,也就是调用Test.java匿名内部类invocationHandler中的invoke()方法。下面对传入的参数进行解释:
this就是调用invoke方法的对象,calculatorService的值,也就是代理对象;
这里的method就是m3,也就是代码最下面静态代码块中加载的ICalculatorService接口中的add方法;
向add中传入的常量值i,j 在这里是先将二者转换成了Integer类型;
InvocationHandler h = new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println(proxy.getClass().getName());
System.out.println(method.getDeclaringClass().getName());
String name = method.getName();
System.out.println(this.getClass().getName()+":The "+name+" method begins.");
System.out.println(this.getClass().getName()+":Parameters of the "+name+" method: ["+args[0]+","+args[1]+"]");
Object result = method.invoke(calculatorService, args);//目标方法
System.out.println(this.getClass().getName()+":Result of the "+name+" method:"+result);
System.out.println(this.getClass().getName()+":The "+name+" method ends.");
return result;
}
};
在这个匿名内部类的invoke方法中,method.invoke(calculatorService, args);这个相当于调用的calculatorService中的add方法,将得到的结果返回给result;匿名内部类的invoke方法执行结束,代理类中的super.h.invoke(this, m3, new Object[] {Integer.valueOf(i), Integer.valueOf(j);这部分代码执行结束。由于匿名内部类的invoke方法是Object类,所以要将其转换成Integer类,再调用intValue(),将其转换成int类型。至此代理类中的add方法结束,并将结果返回给Test中main方法第五行里面的result,Test中main方法第五行代码也执行结束。
第六行:输出得到的结果。
总结:
1)Interface:对于JDK proxy,业务类是需要一个Interface的,这是一个缺陷
2)Proxy,Proxy 类是动态产生的,这个类在调用Proxy.newProxyInstance(targetCls.getClassLoader, targetCls.getInterface,InvocationHander)之后,会产生一个Proxy类的实例。实际上这个Proxy类也是存在的,不仅仅是类的实例。这个Proxy类可以保存到硬盘上。
3) Method:对于业务委托类的每个方法,现在Proxy类里面都不用静态显示出来
4) InvocationHandler: 这个类在业务委托类执行时,会先调用invoke方法。invoke方法再执行相应的代理操作,可以实现对业务方法的再包装
除了jdk动态代理,还有一种叫做CGLib动态代理:
程序执行时通过ASM(开源的Java字节码编辑库,操作字节码)jar包动态地为被代理类生成一个代理子类,通过该代理子类创建代理对象,由于存在继承关系,所以父类不能使用final修饰。
JDK动态代理与CGLib动态代理区别:
1、JDK动态代理基于接口实现,所以实现JDK动态代理,必须先定义接口;CGLib动态代理基于类实现;
2、JDK动态代理机制是委托机制,委托hanlder调用原始实现类方法;CGLib则使用继承机制,被代理类和代理类是继承关系,所以代理类是可以赋值给被代理类的,如果被代理类有接口,那么代理类也可以赋值给接口。