前言
Java动态代理通过反射的机制实现在运行时,基于传入的指定一组接口及委托类对象,动态的产生代理类,代理类负责将所有的方法调用分派到委托对象上反射执行。动态代理类的创建十分简单:
InvocationHandler handler = new MyInvocationHandler(...);
Class proxyClass = Proxy.getProxyClass(
Foo.class.getClassLoader(), new Class[] { Foo.class });
Foo f = (Foo) proxyClass.
getConstructor(new Class[] { InvocationHandler.class }).
newInstance(new Object[] { handler });
或者
Foo f = (Foo) Proxy.newProxyInstance(Foo.class.getClassLoader(),
new Class[] { Foo.class },
handler);
有动态代理,那一定有静态代理。所以我们先从静态代理看起,一步步分析Java的动态代理机制。
静态代理
说到静态代理,其实就是我们手工对代理模式的实现。代理模式是什么呢?
代理是一种常用的设计模式,其目的就是为其他对象提供一个代理以控制对某个对象的访问。代理类负责为委托类预处理消息,过滤消息并转发消息,以及进行消息被委托类执行后的后续处理。
代理模式的UML图如下所示:
Markdown
为了保持行为的一致性,代理类和委托类通常会实现相同的接口,所以在访问者看来两者没有丝毫的区别。通过代理类这中间一层,能有效控制对委托类对象的直接访问,也可以很好地隐藏和保护委托类对象,同时也为实施不同控制策略预留了空间,从而在设计上获得了更大的灵活性。
我们看一个简单的代理模式的例子:
public interface Bird {
public void fly();
}
public class RealBird implements Bird {
private String name;
public RealBird(String name) {
this.name = name;
}
public void fly() {
System.out.println(String.format("%s is flying...", name));
}
}
public class ProxyBird implements Bird{
private String name;
private Bird bird;
public ProxyBird(String name) {
this.name = name;
}
public void fly() {
if (null == bird){
this.bird = new RealBird(name);
}
bird.fly();
}
}
public class ProxyExample {
public static void main(String[] args){
Bird eagle = new RealBird("eagle");
Bird swan = new ProxyBird("swan");
eagle.fly();
swan.fly();
}
}
eagle is flying...
swan is flying...
代理模式使得代理类控制了客户端对委托类的访问,这使得我们可以在代理类中做一些其他的操作,如日志记录、统计、缓存等,这些都是对用户隐藏的。同时代理类实现与委托类相同接口,代理模式的使用对用户来说是透明的。
Java动态代理使得我们不必手写大量代理类,通过反射方式,在使用时动态的生成代理类。
动态代理
相关类与接口
动态代理的核心就在于java.lang.reflect.Proxy类与java.lang.reflect.InvocationHandler这个接口。
- Proxy类:它是Java动态代理的生成器,它提供了以下静态方法来生成动态代理类。
public static Class<?> getProxyClass(ClassLoader loader,
Class<?>... interfaces);//根据传入的类加载器、接口生成代理类对象
public static Object newProxyInstance(ClassLoader loader,
Class<?>[] interfaces,
InvocationHandler h);//根据传入的类加载器、接口、调用处理器动态生成代理类
public static InvocationHandler getInvocationHandler(Object proxy);//获取代理类对应的调用处理器
- InvocationHandler
public Object invoke(Object proxy, Method method, Object[] args);//调用处理器接口,每个动态类必须关联一个InvocationHandler,通过反射在代理类上执行传入的方法。
源码分析
我们通过一个简单的动态代理的例子来具体分析动态代理机制。
public interface Subject {
public void doSomething();
}
public class RealSubject implements Subject{
public void doSomething() {
System.out.println("do something...");
}
}
public class ProxyInvocationHandler implements InvocationHandler{
private Object proxies;
public ProxyInvocationHandler(Object proxies){
this.proxies = proxies;
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object result = null;
//此处可以做一些方法调用的前置操作
PrintUtil.print(String.format("proxy:%s,method:%s,args:%s", proxies,method,args));
result = method.invoke(proxies, args);
//此处可以做一些方法调用的后置操作
return result;
}
}
public class ProxyTest {
public static void main(String[] args){
Subject realSubject = new RealSubject();//实际对象
Subject subject = (Subject)Proxy.newProxyInstance(Subject.class.getClassLoader(), new Class[]{Subject.class}, new ProxyInvocationHandler(realSubject));
subject.doSomething();
}
}
do something...
从上面的简单例子我们可以总结出使用Java的动态代理的几个步骤:
我们从Proxy类的静态方法newProxyInstance开始追踪起,源码如下:
public static Object newProxyInstance(ClassLoader loader,
Class<?>[] interfaces,
InvocationHandler h)
throws IllegalArgumentException{
if (h == null) {
throw new NullPointerException();
}
final Class<?>[] intfs = interfaces.clone();//复制interfaces接口数组
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 {
final Constructor<?> cons = cl.getConstructor(constructorParams);//获取代理类的构造器对象
final InvocationHandler ih = h;
if (sm != null && ProxyAccessHelper.needsNewInstanceCheck(cl)) {
// create proxy instance with doPrivilege as the proxy class may
// implement non-public interfaces that requires a special permission
return AccessController.doPrivileged(new PrivilegedAction<Object>() {
public Object run() {
return newInstance(cons, ih);//实例化一个代理类的实例
}
});
} else {
return newInstance(cons, ih);
}
} catch (NoSuchMethodException e) {
throw new InternalError(e.toString());
}
}
/**
* Generate a proxy class. Must call the checkProxyAccess method
* to perform permission checks before calling this.
*/
private static Class<?> getProxyClass0(ClassLoader loader,
Class<?>... interfaces) {
if (interfaces.length > 65535) {//该代理类代理的委托类的接口不能超过65536个
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
//从缓存中获取 由对应的ClassLoader加载的实现了对应接口的代理类,如果没有缓存,则先创建一个代理类,然后缓存起来。
return proxyClassCache.get(loader, interfaces);//
}
/**
* a cache of proxy classes
* proxyClassCache 是Proxy实例的私有变量,是一个由WeakCache构成的缓存结构
*/
private static final WeakCache<ClassLoader, Class<?>[], Class<?>>
proxyClassCache = new WeakCache<>(new KeyFactory(), new ProxyClassFactory());
WeakCache的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);
}
}
}
}
而代理类的生成是通过ProxyClassFactory来完成的。生成代理类的核心逻辑是在apply方法中,我们继续分析:
/**
* A factory function that generates, defines and returns the proxy class given
* the ClassLoader and array of interfaces.
*/
private static final class ProxyClassFactory
implements BiFunction<ClassLoader, Class<?>[], Class<?>>
{
// prefix for all proxy class names 所有代理类都有一个$Proxy前缀
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
/*
* 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)) {
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);//此处生成代理类字节码文件
try {
return defineClass0(loader, proxyName,
proxyClassFile, 0, proxyClassFile.length);//类加载器把该类的字节码加载进内存升策划那个该类的class对象
} 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());
}
}
}
最后是通过JDK自带的字节码生成工具类ProxyGenerator,根据传入的代理类名以及代理类需要实现的接口来完成代理类字节码文件的生成:
public static byte[] generateProxyClass(String paramString, Class[] paramArrayOfClass) {
ProxyGenerator localProxyGenerator = new ProxyGenerator(paramString, paramArrayOfClass);
byte[] arrayOfByte = localProxyGenerator.generateClassFile();
if (saveGeneratedFiles)
AccessController.doPrivileged(new PrivilegedAction(paramString, arrayOfByte) {
public Void run() {
try {
FileOutputStream localFileOutputStream = new FileOutputStream(
ProxyGenerator.access$000(this.val$name) + ".class");
localFileOutputStream.write(this.val$classFile);
localFileOutputStream.close();
return null;
} catch (IOException localIOException) {
throw new InternalError("I/O exception saving generated file: " + localIOException);
}
}
});
return arrayOfByte;
}
generateProxyClass方法生成代理类的核心在于generateClassFile方法,该方法的主要工作就是根据JAVA字节码规范,根据我们设定的目的-生成一个带有一些接口的代理类,最终在内存中生成该代理类的字节码流,然后写入磁盘,最终该代理类就生成了。然后类加载器加载该字节码,我们就可以在程序中使用该代理类了。
注:我们在generateProxyClass方法中可以看到一点,当saveGeneratedFiles为true时,我们才会执行后面的把生成的代理类写到磁盘存储下来。但saveGeneratedFiles的值是在哪里设置的呢?查找ProxyGenerator类,发现:
private static final boolean saveGeneratedFiles;
static {
saveGeneratedFiles = ((Boolean) AccessController
.doPrivileged(new GetBooleanAction("sun.misc.ProxyGenerator.saveGeneratedFiles"))).booleanValue();
try {
hashCodeMethod = Object.class.getMethod("hashCode", new Class[0]);
equalsMethod = Object.class.getMethod("equals", new Class[] { Object.class });
toStringMethod = Object.class.getMethod("toString", new Class[0]);
} catch (NoSuchMethodException localNoSuchMethodException) {
throw new NoSuchMethodError(localNoSuchMethodException.getMessage());
}
}
ProxyGenerator类初始化的时候,会去系统属性里查找‘sun.misc.ProxyGenerator.saveGeneratedFiles’属性的val并赋值给saveGeneratedFiles。所以很清楚了,我们只需要在系统Property里设置 ‘sun.misc.ProxyGenerator.saveGeneratedFiles’属性为true,我们使用的动态代理类就会落地到磁盘上了。
我们运行一下该代理类:
public class ProxyTest {
public static void main(String[] args){
System.setProperty("sun.misc.ProxyGenerator.saveGeneratedFiles", "true");
Subject sub = new RealSubject();
Subject proxy = (Subject)Proxy.newProxyInstance(sub.getClass().getClassLoader(), sub.getClass().getInterfaces(), new ProxyInvocationHandler(sub));
proxy.doSomething();
}
}
报错:
Exception in thread "main" java.lang.InternalError: I/O exception saving generated file: java.io.FileNotFoundException: com\sun\proxy$Proxy0.class (系统找不到指定的路径。)
手动创建目录,得到落地的动态代理类$Proxy0字节码文件,反编译得到:
public final class $Proxy0 extends Proxy
implements Subject
{
private static Method m1;
private static Method m0;
private static Method m3;
private static Method m2;
public $Proxy0(InvocationHandler paramInvocationHandler)
throws
{
super(paramInvocationHandler);
}
public final boolean equals(Object paramObject)
throws
{
try
{
return ((Boolean)this.h.invoke(this, m1, new Object[] { paramObject })).booleanValue();
}
catch (Error|RuntimeException localError)
{
throw localError;
}
catch (Throwable localThrowable)
{
throw new UndeclaredThrowableException(localThrowable);
}
}
public final int hashCode()
throws
{
try
{
return ((Integer)this.h.invoke(this, m0, null)).intValue();
}
catch (Error|RuntimeException localError)
{
throw localError;
}
catch (Throwable localThrowable)
{
throw new UndeclaredThrowableException(localThrowable);
}
}
public final void doSomething()
throws
{
try
{
this.h.invoke(this, m3, null);
return;
}
catch (Error|RuntimeException localError)
{
throw localError;
}
catch (Throwable localThrowable)
{
throw new UndeclaredThrowableException(localThrowable);
}
}
public final String toString()
throws
{
try
{
return (String)this.h.invoke(this, m2, null);
}
catch (Error|RuntimeException localError)
{
throw localError;
}
catch (Throwable localThrowable)
{
throw new UndeclaredThrowableException(localThrowable);
}
}
static
{
try
{
m1 = Class.forName("java.lang.Object").getMethod("equals", new Class[] { Class.forName("java.lang.Object") });
m0 = Class.forName("java.lang.Object").getMethod("hashCode", new Class[0]);
m3 = Class.forName("com.xxxx.book.zzm.chap7.proxy.Subject").getMethod("doSomething", new Class[0]);
m2 = Class.forName("java.lang.Object").getMethod("toString", new Class[0]);
return;
}
catch (NoSuchMethodException localNoSuchMethodException)
{
throw new NoSuchMethodError(localNoSuchMethodException.getMessage());
}
catch (ClassNotFoundException localClassNotFoundException)
{
throw new NoClassDefFoundError(localClassNotFoundException.getMessage());
}
}
}
总结
以上就是我们对Java动态代理机制的分析,通过源码分析,我们知道了jdk是通过代理类生成器生成了代理类。通过对全局属性‘sun.misc.ProxyGenerator.saveGeneratedFiles’的设置,该动态类可以落地到磁盘。
参考
- jdk1.7源码
网友评论