1.首先新建一个接口Subject
public interface Subject {
public void doSomething();
}
2. 然后为接口新建一个实现类RealSubject
public class RealSubject implements Subject{
@Override
public void doSomething() {
System.out.println("fly...");
}
}
3. 接着创建一个代理类ProxyHandler实现java.lang.reflect.InvocationHandler
接口,重写invoke方法
public class ProxyHandler implements InvocationHandler{
private Object target;
public Object bind(Object target){
this.target = target;
// 绑定该类实现的所有接口,取得代理类
return Proxy.newProxyInstance(
target.getClass().getClassLoader(),
target.getClass().getInterfaces(),
this);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// 在调用具体函数方法前,执行功能处理
System.out.println("before.");
// 反射执行目标类的方法
Object result = method.invoke(target,args);
System.out.println("after.");
// 在调用具体函数方法后,执行功能处理
return result;
}
public static void main(String[] args) {
ProxyHandler proxy = new ProxyHandler();
// 绑定该类实现的所有接口
Subject sub = (Subject) proxy.bind(new RealSubject());
sub.doSomething();
}
}
4. 输出结果
before.
fly...
after.
首先看Proxy
类中的newProxyInstance
方法
public Object bind(Object target){
this.target = target;
// 绑定该类实现的所有接口,取得代理类
return Proxy.newProxyInstance(
target.getClass().getClassLoader(),
target.getClass().getInterfaces(),
this);
}
public static Object newProxyInstance(ClassLoader loader,
Class>[] interfaces,
InvocationHandler h)
throws IllegalArgumentException
{
// 判断InvocationHandler是否为空,若为空,抛出空指针异常
Objects.requireNonNull(h);
final Class>[] intfs = interfaces.clone();
final SecurityManager sm = System.getSecurityManager();
if (sm != null) {
checkProxyAccess(Reflection.getCallerClass(), loader, intfs);
}
/*
* 生成接口的代理类的字节码文件
*/
Class> cl = getProxyClass0(loader, intfs);
/*
* 使用自定义的InvocationHandler作为参数,调用构造函数获取代理类对象实例
*/
try {
if (sm != null) {
checkNewProxyPermission(Reflection.getCallerClass(), cl);
}
// 获取代理类的构造函数,入参为InvocationHandler
final Constructor> cons = cl.getConstructor(constructorParams);
final InvocationHandler ih = h;
if (!Modifier.isPublic(cl.getModifiers())) {
AccessController.doPrivileged(new PrivilegedAction() {
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);
}
}
newProxyInstance
方法调用getProxyClass0(loader, intfs)
方法生成代理类的字节码文件。
private static Class> getProxyClass0(ClassLoader loader,
Class>... interfaces) {
// 限定代理的接口不能超过65535个
if (interfaces.length > 65535) {
throw new IllegalArgumentException("interface limit exceeded");
}
// 如果缓存中已经存在相应接口的代理类,直接返回;否则,使用ProxyClassFactory创建代理类
return proxyClassCache.get(loader, interfaces);
}
其中proxyClassCache = new WeakCache<>(new KeyFactory(), new ProxyClassFactory());
缓存使用的是WeakCache实现的,此处主要关注使用ProxyClassFactory创建代理的情况。ProxyClassFactory是Proxy类的静态内部类,实现了BiFunction接口,实现了BiFunction接口中的apply
方法。
当WeakCache中没有缓存相应接口的代理类,则会调用ProxyClassFactory类的apply
方法来创建代理类。
proxyClassCache.get(loader, interfaces);
方法就不跟了
private static final class ProxyClassFactory
implements BiFunction[], Class>>
{
// 代理类前缀
private static final String proxyClassNamePrefix = "$Proxy";
// 生成代理类名称的计数器
private static final AtomicLong nextUniqueNumber = new AtomicLong();
@Override
public Class> apply(ClassLoader loader, Class>[] interfaces) {
Map, Boolean> interfaceSet = new IdentityHashMap<>(interfaces.length);
for (Class> intf : interfaces) {
/*
* 校验类加载器是否能通过接口名称加载该类
* 这个加载器是被代理目标类的加载器
*/
Class> interfaceClass = null;
try {
interfaceClass = Class.forName(intf.getName(), false, loader);
} catch (ClassNotFoundException e) {
}
if (interfaceClass != intf) {
throw new IllegalArgumentException(
intf + " is not visible from class loader");
}
/*
* 校验该类是否是接口
*/
if (!interfaceClass.isInterface()) {
throw new IllegalArgumentException(
interfaceClass.getName() + " is not an interface");
}
/*
* 校验接口是否重复
*/
if (interfaceSet.put(interfaceClass, Boolean.TRUE) != null) {
throw new IllegalArgumentException(
"repeated interface: " + interfaceClass.getName());
}
}
String proxyPkg = null; // 代理类包名
int accessFlags = Modifier.PUBLIC | Modifier.FINAL;
/*
* 非public接口,代理类的包名与接口的包名相同
*/
for (Class> intf : interfaces) {
int flags = intf.getModifiers();
if (!Modifier.isPublic(flags)) {
accessFlags = Modifier.FINAL;
String name = intf.getName();
int n = name.lastIndexOf('.');
String pkg = ((n == -1) ? "" : name.substring(0, n + 1));
if (proxyPkg == null) {
proxyPkg = pkg;
} else if (!pkg.equals(proxyPkg)) {
throw new IllegalArgumentException(
"non-public interfaces from different packages");
}
}
}
if (proxyPkg == null) {
// public代理接口,使用com.sun.proxy包名
proxyPkg = ReflectUtil.PROXY_PACKAGE + ".";
}
/*
* 为代理类生成名字
* com.sun.proxy.$Proxy0
*/
long num = nextUniqueNumber.getAndIncrement();
String proxyName = proxyPkg + proxyClassNamePrefix + num;
/*
* 真正生成代理类的字节码文件的地方
*/
byte[] proxyClassFile = ProxyGenerator.generateProxyClass(
proxyName, interfaces, accessFlags);
try {
// 使用类加载器将代理类的字节码文件加载到JVM中,native方法
return defineClass0(loader, proxyName,
proxyClassFile, 0, proxyClassFile.length);
} catch (ClassFormatError e) {
/*
* A ClassFormatError here means that (barring bugs in the
* proxy class generation code) there was some other
* invalid aspect of the arguments supplied to the proxy
* class creation (such as virtual machine limitations
* exceeded).
*/
throw new IllegalArgumentException(e.toString());
}
}
}
在ProxyClassFactory类的apply
方法中可看出真正生成代理类字节码的地方是ProxyGenerator类中的generateProxyClass
public static byte[] generateProxyClass(final String var0, Class>[] var1, int var2) {
ProxyGenerator var3 = new ProxyGenerator(var0, var1, var2);
// 生成代理类的字节码
final byte[] var4 = var3.generateClassFile();
// 是否要将生成代理类的字节码文件保存到磁盘中,该变量可以通过系统属性设置
if (saveGeneratedFiles) {
AccessController.doPrivileged(new PrivilegedAction() {
public Void run() {
try {
int var1 = var0.lastIndexOf(46);
Path var2;
if (var1 > 0) {
Path var3 = Paths.get(var0.substring(0, var1).replace('.', File.separatorChar));
Files.createDirectories(var3);
var2 = var3.resolve(var0.substring(var1 + 1, var0.length()) + ".class");
} else {
var2 = Paths.get(var0 + ".class");
}
// 将文件写入磁盘
Files.write(var2, var4, new OpenOption[0]);
return null;
} catch (IOException var4x) {
throw new InternalError("I/O exception saving generated file: " + var4x);
}
}
});
}
return var4;
}
看看ProxyGenerator的generateClassFile()
方法,抽出一些重点看
// 添加hashCode、equals、toString方法
this.addProxyMethod(hashCodeMethod, Object.class);
this.addProxyMethod(equalsMethod, Object.class);
this.addProxyMethod(toStringMethod, Object.class);
// 遍历目标类接口的方法
Class[] var1 = this.interfaces;
int var2 = var1.length;
int var3;
Class var4;
for(var3 = 0; var3 < var2; ++var3) {
var4 = var1[var3];
Method[] var5 = var4.getMethods();
int var6 = var5.length;
for(int var7 = 0; var7 < var6; ++var7) {
Method var8 = var5[var7];
// 添加接口的方法
this.addProxyMethod(var8, var4);
}
}
添加构造函数,参数为InvocationHandler
this.methods.add(this.generateConstructor());
private ProxyGenerator.MethodInfo generateConstructor() throws IOException {
ProxyGenerator.MethodInfo var1 = new ProxyGenerator.MethodInfo("", "(Ljava/lang/reflect/InvocationHandler;)V", 1);
DataOutputStream var2 = new DataOutputStream(var1.code);
this.code_aload(0, var2);
this.code_aload(1, var2);
var2.writeByte(183);
var2.writeShort(this.cp.getMethodRef("java/lang/reflect/Proxy", "", "(Ljava/lang/reflect/InvocationHandler;)V"));
var2.writeByte(177);
var1.maxStack = 10;
var1.maxLocals = 2;
var1.declaredExceptions = new short[0];
return var1;
}
最后输出为字节
在测试案例中,设置系统属性sun.misc.ProxyGenerator.saveGeneratedFiles
值为true
程序中根据这个判断是否将生成代理类的字节码保存到磁盘
public static void main(String[] args) {
// 保存生成的代理类的字节码文件
System.getProperties().put("sun.misc.ProxyGenerator.saveGeneratedFiles", "true");
ProxyHandler proxy = new ProxyHandler();
// 绑定该类实现的所有接口
Subject sub = (Subject) proxy.bind(new RealSubject());
sub.doSomething();
}
package com.sun.proxy;
import com.yk.demo.dynamicProxy.Subject;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.lang.reflect.UndeclaredThrowableException;
public final class $Proxy0 extends Proxy implements Subject {
private static Method m1;
private static Method m3;
private static Method m2;
private static Method m0;
public $Proxy0(InvocationHandler var1) throws {
super(var1);
}
public final boolean equals(Object var1) throws {
try {
return ((Boolean)super.h.invoke(this, m1, new Object[]{var1})).booleanValue();
} catch (RuntimeException | Error var3) {
throw var3;
} catch (Throwable var4) {
throw new UndeclaredThrowableException(var4);
}
}
public final void doSomething() throws {
try {
super.h.invoke(this, m3, (Object[])null);
} catch (RuntimeException | Error var2) {
throw var2;
} catch (Throwable var3) {
throw new UndeclaredThrowableException(var3);
}
}
public final String toString() throws {
try {
return (String)super.h.invoke(this, m2, (Object[])null);
} catch (RuntimeException | Error var2) {
throw var2;
} catch (Throwable var3) {
throw new UndeclaredThrowableException(var3);
}
}
public final int hashCode() throws {
try {
return ((Integer)super.h.invoke(this, m0, (Object[])null)).intValue();
} catch (RuntimeException | Error var2) {
throw var2;
} catch (Throwable var3) {
throw new UndeclaredThrowableException(var3);
}
}
static {
try {
m1 = Class.forName("java.lang.Object").getMethod("equals", Class.forName("java.lang.Object"));
m3 = Class.forName("com.yk.demo.dynamicProxy.Subject").getMethod("doSomething");
m2 = Class.forName("java.lang.Object").getMethod("toString");
m0 = Class.forName("java.lang.Object").getMethod("hashCode");
} catch (NoSuchMethodException var2) {
throw new NoSuchMethodError(var2.getMessage());
} catch (ClassNotFoundException var3) {
throw new NoClassDefFoundError(var3.getMessage());
}
}
}
可看到
1、代理类继承了Proxy类并且实现了要代理的接口,由于java不支持多继承,所以JDK动态代理不能代理类
2、重写了equals、hashCode、toString
3、有一个静态代码块,通过反射初始化了代理类的方法
4、通过invoke执行代理类中的目标方法doSomething
$Proxy0.class的实例化
前面讲过,通过构造函数实例化对象,入参是就是Proxy.newProxyInstance
传进来的InvocationHandler
public $Proxy0(InvocationHandler var1) throws {
super(var1);
}
先调用父类Proxy的构造方法
protected Proxy(InvocationHandler h) {
Objects.requireNonNull(h);
this.h = h;
}
代理类 $Proxy0执行方法时,总是调用super.h.invoke
public final void doSomething() throws {
try {
super.h.invoke(this, m3, (Object[])null);
} catch (RuntimeException | Error var2) {
throw var2;
} catch (Throwable var3) {
throw new UndeclaredThrowableException(var3);
}
}
super
就是Proxy
h
就是自定义动态代理处理类ProxyHandler
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// 在调用具体函数方法前,执行功能处理
System.out.println("before.");
// 反射执行目标类的方法
Object result = method.invoke(target,args);
System.out.println("after.");
// 在调用具体函数方法后,执行功能处理
return result;
}
根据java面向对象知道,所有的类都有最终继承Object,而Object中默认实现了equals、toString与hashCode方法。
因为代理类继承了Proxy,所以如果不重写equals、toString与hashCode方法
那么当代理类执行equals、toString与hashCode方法时,实现的就是Proxy中的方法,也就是Object中的方法
但是如果目标类重写了equals、toString与hashCode方法,这时就会出现问题了。
所以代理必须重写equals、toString与hashCode方法,通过反射执行目标类的equals、toString与hashCode方法