1.代理模式:给用户对象提供一个代理对象,由代理对象来控制对委托类的引用,就像生活中的中介:
2.使用代理模式的好处
1.由于代理对象和委托类实现的接口相同.当用户对象不能或者不方便持有委托类对象时,可以通过代理对象来完成委托类方法的调用,代理对象起到一个中介的作用.也可用来隔离用户和服务
2.符合开闭原则,可以拓展委托类方法.当委托类方法不满足用户对象时,可以通过代理类来进行委托类的方法拓展而不必直接修改委托类.符合开闭原则.代理类主要进行消息预处理,消息的过滤,转发消息给委托类.代理类并不真正实现服务内容.真正的业务是由委托类来实现的,代理类是依靠调用委托类方法来完成服务的调用,因此代理类在调用委托类方法的前后可以拓展公共方法.比如增加日志或者上报信息等
代理模式的实现:
1.静态代理:每一个委托类对应一个代理类,由程序员手动编写,弊端:多个委托类需要编写多个代理类,接口有变化的时候需要修改多个代理类
2.动态代理:可以由 Jdk 通过反射动态生成代理类对象,减少了代码量,同时减少了对业务接口的依赖性.降低了耦合度, 弊端:反射生成代理类对象相较静态代理更耗时,只能支持对接口的代理.动态生成的代理类均有同一个父类为 Proxy.由于 java 的单继承的特性.导致了动态代理不能支持对 Class 的代理
jdk 动态生成代理对象的解析:
时序图如下:
代码分析:
Proxy类中:
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);//获取代理类的Class对象
/*
* 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);
}
}
方法中 Class<?> cl = getProxyClass0(loader, intfs) 获取到代理类的 Class 对象.跟进 getProxyClass()方法中:
private static Class<?> getProxyClass0(ClassLoader loader,
Class<?>... interfaces) {
if (interfaces.length > 65535) { //校验接口数量不超过 65535
throw new IllegalArgumentException("interface limit exceeded");
}
// If the proxy class defined by the given loader implementing
// the given interfaces exists, this will simply return the cached copy;
// otherwise, it will create the proxy class via the ProxyClassFactory
return proxyClassCache.get(loader, interfaces);//获取 Class 对象
}
其中 ProxyClassCache 是 WeakCache<K, P, V> 类的对象.跟进 get 方法中:
public V get(K key, P parameter) {
Objects.requireNonNull(parameter);
expungeStaleEntries();
Object cacheKey = CacheKey.valueOf(key, refQueue);
// lazily install the 2nd level valuesMap for the particular cacheKey
ConcurrentMap<Object, Supplier<V>> valuesMap = map.get(cacheKey);
if (valuesMap == null) {
ConcurrentMap<Object, Supplier<V>> oldValuesMap
= map.putIfAbsent(cacheKey,
valuesMap = new ConcurrentHashMap<>());
if (oldValuesMap != null) {
valuesMap = oldValuesMap;
}
}
// create subKey and retrieve the possible Supplier<V> stored by that
// subKey from valuesMap
//获取代理类对象
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;
}
}
// else no supplier in cache
// or a supplier that returned null (could be a cleared CacheValue
// or a Factory that wasn't successful in installing the CacheValue)
// lazily construct a Factory
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)) {
// successfully replaced
// cleared CacheEntry / unsuccessful Factory
// with our Factory
supplier = factory;
} else {
// retry with current supplier
supplier = valuesMap.get(subKey);
}
}
}
}
get()方法中由subKeyFactory.apply(key, parameter) 获取代理类实例对象.其中 subKeyFactory 变量为BiFunction<K, P, ?>实现类的实例.查看实现类可以追踪到Proxy 的内部类 ProxyClassFactory 类.由此查看 ProxyClassFactory 内的 apply () 方法:
@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.
*生成代理类 Class类的 class 文件的二进制数组
*/
byte[] proxyClassFile = ProxyGenerator.generateProxyClass(
proxyName, interfaces, accessFlags);
try {
//defineClass0() 此为 native 方法,由本地 C语言方法根据字节数组生成代理类对象
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());
}
}
}
apply()方法中.byte[] proxyClassFile = ProxyGenerator.generateProxyClass(proxyName,interfaces,accessFlags),该方法生成代理类的.class 文件的字节数组返回,并将.class二进制文件保存至本地或者内存中.java 类实例对象加载过程如下:
下面可以用工具类将动态生成的代理类的.class 文件保存至本地目录.将其反编译为 java 文件看一下jdk 生成代理类的代码:
工具方法为:
public static void generateClassFile(Class clazz,String proxyName){
/*ProxyGenerator.generateProxyClass(
proxyName, interfaces, accessFlags);*/
byte[] proxyClassFile =ProxyGenerator.generateProxyClass(
proxyName, new Class[]{clazz});
String paths = clazz.getResource(".").getPath();
System.out.println(paths);
FileOutputStream out = null;
try {
out = new FileOutputStream(paths+proxyName+".class");
out.write(proxyClassFile);
out.flush();
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
生成的.class 文件反编译后的代码如下:
import exce.DzCarFactory;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.lang.reflect.UndeclaredThrowableException;
public final class dz extends Proxy implements IFactory {
private static Method m1;
private static Method m3;
private static Method m8;
private static Method m2;
private static Method m5;
private static Method m4;
private static Method m7;
private static Method m9;
private static Method m0;
private static Method m6;
public dz(InvocationHandler paramInvocationHandler) {
super(paramInvocationHandler);
}
public final boolean equals(Object paramObject) {
try {
return ((Boolean)this.h.invoke(this, m1, new Object[] { paramObject })).booleanValue();
} catch (Error|RuntimeException error) {
throw null;
} catch (Throwable throwable) {
throw new UndeclaredThrowableException(throwable);
}
}
public final void product(String paramString) {
try {
this.h.invoke(this, m3, new Object[] { paramString });
return;
} catch (Error|RuntimeException error) {
throw null;
} catch (Throwable throwable) {
throw new UndeclaredThrowableException(throwable);
}
}
public final void notify() {
try {
this.h.invoke(this, m8, null);
return;
} catch (Error|RuntimeException error) {
throw null;
} catch (Throwable throwable) {
throw new UndeclaredThrowableException(throwable);
}
}
public final String toString() {
try {
return (String)this.h.invoke(this, m2, null);
} catch (Error|RuntimeException error) {
throw null;
} catch (Throwable throwable) {
throw new UndeclaredThrowableException(throwable);
}
}
public final void wait(long paramLong) throws InterruptedException {
try {
this.h.invoke(this, m5, new Object[] { Long.valueOf(paramLong) });
return;
} catch (Error|RuntimeException|InterruptedException error) {
throw null;
} catch (Throwable throwable) {
throw new UndeclaredThrowableException(throwable);
}
}
public final void wait(long paramLong, int paramInt) throws InterruptedException {
try {
this.h.invoke(this, m4, new Object[] { Long.valueOf(paramLong), Integer.valueOf(paramInt) });
return;
} catch (Error|RuntimeException|InterruptedException error) {
throw null;
} catch (Throwable throwable) {
throw new UndeclaredThrowableException(throwable);
}
}
public final Class getClass() {
try {
return (Class)this.h.invoke(this, m7, null);
} catch (Error|RuntimeException error) {
throw null;
} catch (Throwable throwable) {
throw new UndeclaredThrowableException(throwable);
}
}
public final void notifyAll() {
try {
this.h.invoke(this, m9, null);
return;
} catch (Error|RuntimeException error) {
throw null;
} catch (Throwable throwable) {
throw new UndeclaredThrowableException(throwable);
}
}
public final int hashCode() {
try {
return ((Integer)this.h.invoke(this, m0, null)).intValue();
} catch (Error|RuntimeException error) {
throw null;
} catch (Throwable throwable) {
throw new UndeclaredThrowableException(throwable);
}
}
public final void wait() throws InterruptedException {
try {
this.h.invoke(this, m6, null);
return;
} catch (Error|RuntimeException|InterruptedException error) {
throw null;
} catch (Throwable throwable) {
throw new UndeclaredThrowableException(throwable);
}
}
static {
try {
m1 = Class.forName("java.lang.Object").getMethod("equals", new Class[] { Class.forName("java.lang.Object") });
m3 = Class.forName("exce.DzCarFactory").getMethod("product", new Class[] { Class.forName("java.lang.String") });
m8 = Class.forName("exce.DzCarFactory").getMethod("notify", new Class[0]);
m2 = Class.forName("java.lang.Object").getMethod("toString", new Class[0]);
m5 = Class.forName("exce.DzCarFactory").getMethod("wait", new Class[] { long.class });
m4 = Class.forName("exce.DzCarFactory").getMethod("wait", new Class[] { long.class, int.class });
m7 = Class.forName("exce.DzCarFactory").getMethod("getClass", new Class[0]);
m9 = Class.forName("exce.DzCarFactory").getMethod("notifyAll", new Class[0]);
m0 = Class.forName("java.lang.Object").getMethod("hashCode", new Class[0]);
m6 = Class.forName("exce.DzCarFactory").getMethod("wait", new Class[0]);
return;
} catch (NoSuchMethodException noSuchMethodException) {
throw new NoSuchMethodError(noSuchMethodException.getMessage());
} catch (ClassNotFoundException classNotFoundException) {
throw new NoClassDefFoundError(classNotFoundException.getMessage());
}
}
}
由反编译出的自动生成的代理类代码可以看出:
1.自动生成的代理类均由一个固定的父类为 Proxy,这决定了 jdk 只能动态代理接口;
2.代理类方法的实现是调用 InvocationHandler 实例的 invoke()方法,如 product()方法中:this.h.invoke(this, m3, new Object[] { paramString });其中参数 m3是利用反射的方式根据委托类的包路径+类名,方法名以及参数类型,拿到的委托类对应方法的 Method 对象,this.h 为 InvocationHandler 实例,由 Proxy 类中 newProxyInstance()方法中获取代理类构造方法时传入.因此在使用 jdk 动态代理 api 时,必须实现 InvocationHandler 的 invoke 方法.动态代理对象才能完成对委托类方法的调用
以上为 jdk 动态生成代理类对象的分析.