本文目录
代理模式概述
代理模式是二十三种(Gof)代理模式中的一种结构型设计模式,在代理模式中一般有一个代理对象,代理对象给某个对象提供一个代理,并有代理对象控制对原对象引用。
静态代理模式
静态代理模式中代理类在程序运行前就已经存在。 通常情况下, 静态代理中的代理类和目标类会实现同一接口或是派生自相同的父类。
静态代理模式的结构图如下
抽象主题类
/**
* 抽象主题类,一般在该类中定义一些公共接口
*/
public interface Subject {
public void request();
}
真实主题类
/**
* 真实主题类,该类中定义一些业务实现操作方法
*/
public class RealSubject implements Subject{
@Override
public void request() {
System.out.println("RealSubject request");
}
}
代理主题类
/**
* 代理主题类
* 该类持有真实主题类的引用,从而可以操作真实主题类对外暴露的方法
* 且该类和真实主题类有实现了同样的接口即Subject接口,该类可以替代真实主题类
* 通常在调用真实主题类方法前和后加入一些其他的操作
*/
public class Proxy implements Subject{
RealSubject realSubject = new RealSubject();
@Override
public void request() {
preRequest();
realSubject.request();
postRequest();
}
public void preRequest(){
System.out.println("Proxy preRequest ");
}
public void postRequest(){
System.out.println("Proxy postRequest ");
}
}
测试代码
public class Test {
public static void main(String[] args) {
Subject subject = new Proxy();
subject.request();
}
}
运行结果如下:
动态代理
前面的静态代理模式中代理类在程序运行前就已经存在,而动态代理的代理类在程序运行时创建的。一般我们称运行时创建代理类的代理方式为动态代理。 在Java中有多种动态代理技术,如JDK、CGLIB、Javaassist、ASM,一般最常见的动态代理技术是JDK和CGLIB。
这两种代理类型的使用场景如下:
JDK动态代理:如果目标对象实现了接口,采用JDK的动态代理
CGLIB动态代理:如果目标对象没有实现了接口,必须采用CGLIB动态代理
JDK动态代理
我们先接着前面的例子,写一个简单的动态代理示例。
Subject subject = new RealSubject();
Subject proxy = (Subject) Proxy.newProxyInstance(subject.getClass().getClassLoader(),
subject.getClass().getInterfaces(),
new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
preRequest();
Object obj = method.invoke(subject, args);
postRequest();
return obj;
}
public void preRequest() {
System.out.println("Dynamic Proxy preRequest ");
}
public void postRequest() {
System.out.println("Dynamic Proxy postRequest ");
}
});
proxy.request();
运行结果:
JDK动态代理原理解析
Proxy.newProxyInstance方法
该方法一共有三个参数,分别如下:
loader
:代理类的类加载器
interfaces
:代理类的实现接口
h
:InvocationHandle
r接口的实现类
public static Object newProxyInstance(ClassLoader loader,
Class<?>[] interfaces,
InvocationHandler h){
// 先将传入的interfaces数组克隆
final Class<?>[] intfs = interfaces.clone();
//生成代理类
Class<?> cl = getProxyClass0(loader, intfs);
}
在上面的newProxyInstance()
方法中调用了getProxyClass0()
方法生成代理类,我们再来看一下getProxyClass0()
方法
getProxyClass0()方法
private static Class<?> getProxyClass0(ClassLoader loader,
Class<?>... interfaces) {
if (interfaces.length > 65535) {
throw new IllegalArgumentException("interface limit exceeded");
}
return proxyClassCache.get(loader, interfaces);
}
private static final WeakCache<ClassLoader, Class<?>[], Class<?>>
proxyClassCache = new WeakCache<>(new KeyFactory(), new ProxyClassFactory());
该方法主要对接口数量做了个判断,然后通过缓存proxyClassCache
获取代理类,这儿注意proxyClassCache在初始化时已经初始化了一个KeyFactory
和ProxyClassFactory
WeakCache的get方法
抽去了该方法中的核心代码,可以看到该方法中新建了 Factory factory = new Factory(key, parameter, subKey, valuesMap)
; 并将这个factory赋值给Suplier
调用get方法返回构造的代理类。
public V get(K key, P parameter) {
Object subKey = Objects.requireNonNull(subKeyFactory.apply(key, parameter));
Supplier<V> supplier = valuesMap.get(subKey);
Factory factory = null;
while (true) {
if (supplier != null) {
// supplier might be a Factory or a CacheValue<V> instance
V value = supplier.get();
if (value != null) {
return value;
}
}
if (factory == null) {
factory = new Factory(key, parameter, subKey, valuesMap);
}
if (supplier == null) {
supplier = valuesMap.putIfAbsent(subKey, factory);
if (supplier == null) {
// successfully installed Factory
supplier = factory;
}
// else retry with winning supplier
} else {
if (valuesMap.replace(subKey, supplier, factory)) {
supplier = factory;
} else {
// retry with current supplier
supplier = valuesMap.get(subKey);
}
}
}
}
}
Factory的get方法
该方法的主要作用则是通过valueFactory
创建代理类后 将代理类包装为CacheValue
类,并将valuesMap
缓存中对应代理类的Supplier
替换为包装后的CacheValue
,这样后面就可以直接调用CacheValue的get方法来获取代理类
public synchronized V get() { // serialize access
Supplier<V> supplier = valuesMap.get(subKey);
if (supplier != this) {
return null;
}
V value = null;
try {
value = Objects.requireNonNull(valueFactory.apply(key, parameter));
} finally {
if (value == null) { // remove us on failure
valuesMap.remove(subKey, this);
}
}
assert value != null;
// wrap value with CacheValue (WeakReference)
CacheValue<V> cacheValue = new CacheValue<>(value);
// try replacing us with CacheValue (this should always succeed)
if (valuesMap.replace(subKey, this, cacheValue)) {
// put also in reverseMap
reverseMap.put(cacheValue, Boolean.TRUE);
} else {
throw new AssertionError("Should not reach here");
}
// successfully replaced us with new CacheValue -> return the value
// wrapped by it
return value;
}
}
我们再来看下上面方法中valueFactory
创建代理类valueFactory.apply(key,parameters)
,在前面的weakCache
初始化在构造函数中传入了两个参数,new KeyFactory(), new ProxyClassFactory(),分别对应subKeyFactory和valueFactory,所以这里的valueFactory则代表ProxyClassFactory,所以这里valueFactory.apply实际上就相当于ProxyClassFactory.apply()
再来看一下ProxyClassFactory.apply()方法
ProxyClassFactory.apply()
该类的apply()
方法,先得到代理类的包名proxyPkg
,产生字节码文件proxyClassFile
,根据字节码文件生成代理类class并返回,核心的两个方法为ProxyGenerator.generateProxyClass(proxyName, interfaces, accessFlags); 以及defineClass0(loader, proxyName,proxyClassFile, 0, proxyClassFile.length);
private static final class ProxyClassFactory
implements BiFunction<ClassLoader, Class<?>[], Class<?>>
{
// prefix for all proxy class names
private static final String proxyClassNamePrefix = "$Proxy";
// next number to use for generation of unique proxy class names
private static final AtomicLong nextUniqueNumber = new AtomicLong();
@Override
public Class<?> apply(ClassLoader loader, Class<?>[] interfaces) {
Map<Class<?>, Boolean> interfaceSet = new IdentityHashMap<>(interfaces.length);
for (Class<?> intf : interfaces) {
/*
* Verify that the class loader resolves the name of this
* interface to the same Class object.
*/
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");
}
/*
* Verify that the Class object actually represents an
* interface.
*/
if (!interfaceClass.isInterface()) {
throw new IllegalArgumentException(
interfaceClass.getName() + " is not an interface");
}
/*
* Verify that this interface is not a duplicate.
*/
if (interfaceSet.put(interfaceClass, Boolean.TRUE) != null) {
throw new IllegalArgumentException(
"repeated interface: " + interfaceClass.getName());
}
}
String proxyPkg = null; // package to define proxy class in
int accessFlags = Modifier.PUBLIC | Modifier.FINAL;
/*
* Record the package of a non-public proxy interface so that the
* proxy class will be defined in the same package. Verify that
* all non-public proxy interfaces are in the same package.
*/
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) {
// if no non-public proxy interfaces, use com.sun.proxy package
proxyPkg = ReflectUtil.PROXY_PACKAGE + ".";
}
/*
* Choose a name for the proxy class to generate.
*/
long num = nextUniqueNumber.getAndIncrement();
String proxyName = proxyPkg + proxyClassNamePrefix + num;
/*
* Generate the specified proxy class.
*/
byte[] proxyClassFile = ProxyGenerator.generateProxyClass(
proxyName, interfaces, accessFlags);
try {
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());
}
}
}
generateProxyClass方法
该方法中先创建ProxyGenerator
类生成器,调用var3.generateClassFile()
生成字节数组,再来看一下这里的核心方法generateClassFile
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<Void>() {
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;
}
generateClassFile
private byte[] generateClassFile() {
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);
}
}
Iterator var11 = this.proxyMethods.values().iterator();
List var12;
while(var11.hasNext()) {
var12 = (List)var11.next();
checkReturnTypes(var12);
}
Iterator var15;
try {
this.methods.add(this.generateConstructor());
var11 = this.proxyMethods.values().iterator();
while(var11.hasNext()) {
var12 = (List)var11.next();
var15 = var12.iterator();
while(var15.hasNext()) {
ProxyGenerator.ProxyMethod var16 = (ProxyGenerator.ProxyMethod)var15.next();
this.fields.add(new ProxyGenerator.FieldInfo(var16.methodFieldName, "Ljava/lang/reflect/Method;", 10));
this.methods.add(var16.generateMethod());
}
}
this.methods.add(this.generateStaticInitializer());
} catch (IOException var10) {
throw new InternalError("unexpected I/O Exception", var10);
}
if (this.methods.size() > 65535) {
throw new IllegalArgumentException("method limit exceeded");
} else if (this.fields.size() > 65535) {
throw new IllegalArgumentException("field limit exceeded");
} else {
this.cp.getClass(dotToSlash(this.className));
this.cp.getClass("java/lang/reflect/Proxy");
var1 = this.interfaces;
var2 = var1.length;
for(var3 = 0; var3 < var2; ++var3) {
var4 = var1[var3];
this.cp.getClass(dotToSlash(var4.getName()));
}
this.cp.setReadOnly();
ByteArrayOutputStream var13 = new ByteArrayOutputStream();
DataOutputStream var14 = new DataOutputStream(var13);
try {
var14.writeInt(-889275714);
var14.writeShort(0);
var14.writeShort(49);
this.cp.write(var14);
var14.writeShort(this.accessFlags);
var14.writeShort(this.cp.getClass(dotToSlash(this.className)));
var14.writeShort(this.cp.getClass("java/lang/reflect/Proxy"));
var14.writeShort(this.interfaces.length);
Class[] var17 = this.interfaces;
int var18 = var17.length;
for(int var19 = 0; var19 < var18; ++var19) {
Class var22 = var17[var19];
var14.writeShort(this.cp.getClass(dotToSlash(var22.getName())));
}
var14.writeShort(this.fields.size());
var15 = this.fields.iterator();
while(var15.hasNext()) {
ProxyGenerator.FieldInfo var20 = (ProxyGenerator.FieldInfo)var15.next();
var20.write(var14);
}
var14.writeShort(this.methods.size());
var15 = this.methods.iterator();
while(var15.hasNext()) {
ProxyGenerator.MethodInfo var21 = (ProxyGenerator.MethodInfo)var15.next();
var21.write(var14);
}
var14.writeShort(0);
return var13.toByteArray();
} catch (IOException var9) {
throw new InternalError("unexpected I/O Exception", var9);
}
}
}
获取到字节码生成的类信息后,我们在回到最前面的newProxyInstance
方法中,
代理类cl
有参构造并传入我们自己一开始定义的
InvocationHandler。通过构造函数创建代理类的实例并返回。所以字节码的父类文件中InvocationHandler则是我们创建的并传入的,
public static Object newProxyInstance(ClassLoader loader,
Class<?>[] interfaces,
InvocationHandler h){
// 先将传入的interfaces数组克隆
final Class<?>[] intfs = interfaces.clone();
//生成代理类
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});
}
}
Proxy类的构造方法传入了InvocationHandler 参数,相当于代理类在执行抽象主体类方法时 实际上是通过我们传入的InvocationHandler的invoke方法进行调用。
protected Proxy(InvocationHandler h) {
Objects.requireNonNull(h);
this.h = h;
}