JAVA中JDK动态代理实现机制,源码分析
静态代理
静态代理就是有两个类,一个是被代理类,一个是代理类。
比如
//这是一个被代理类学生
public class Student implements Person{
public String name;
@Override
public void sayHello() {
System.out.println("hello");
}
}
//这是一个静态代理学生的类
package com.zhulinan.demo1;
public class StaticStudentProxy implements Person{
private Person stu;
public StaticStudentProxy(Person stu) {
this.stu = stu;
}
@Override
public void sayHello() {
System.out.println("我是学生代理,学生让我和你说:");
this.stu.sayHello();
}
}
//测试类
import org.junit.Test;
public class StudentProxyTest {
@Test
public void Test(){
Student student = new Student();
StaticStudentProxy staticStudentProxy = new StaticStudentProxy(student);
staticStudentProxy.sayHello();
}
}
运行结果:
我是学生代理,学生让我和你说:
hello
静态代理,就是代理设计模式的一种最简单的体现,但是缺点也很明显,每次有人要代理的时候,都得写一个静态代理类,比如说我作为一个代理,我只能代理学生或者代理老师或者代理工人,但是一个代理对应一个Person的实现。当代理变化的时候,每个代理类也都得修改代码。那么有没有什么可以代理所有Person实现类的方法呢,比如只要你有sayHello方法,我就可以代理,你有别的方法我也可以代理,当方法没有了我就不代理了,之类的功能的方法呢。 这就引出动态代理
动态代理
动态代理做了什么?动态代理也是返回一个代理类,这个类可以根据你传入的类私人订制,而且对于哪些方法需要动态代理也可以私人订制。既然说到了可以根据类私人订制代理,那么肯定要涉及到获取每个类的class信息,所以动态代理也就是基于反射实现的。
动态代理基于反射里的import java.lang.reflect.Proxy;
//动态代理类
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class DynamicStudentProxy {
public Person CreateProxy(Person person){
Person dynamicStudentProxy = (Person) Proxy.newProxyInstance(person.getClass().getClassLoader(), person.getClass().getInterfaces(), new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (method.getName().equals("sayHello")){
System.out.println("(代理人心里想:发现被代理类要sayHello,这是我的工作我得帮他说)");
System.out.println("我是学生代理,学生让我和你说:");
return method.invoke(person,args);
}
return method.invoke(person,args);
}
});
return dynamicStudentProxy;
}
}
//测试类
import org.junit.Test;
public class StudentProxyTest {
@Test
public void Test(){
Student student = new Student();
StaticStudentProxy staticStudentProxy = new StaticStudentProxy(student);
staticStudentProxy.sayHello();
}
@Test
public void TestDynamicProxy(){
Person student = new Student();
DynamicStudentProxy dynamicStudentProxy = new DynamicStudentProxy();
Person studentProxy = dynamicStudentProxy.CreateProxy(student);
studentProxy.sayHello();
}
}
运行结果:
(代理人心里想:发现被代理类要sayHello,这是我的工作我得帮他说)
我是学生代理,学生让我和你说:
hello
宏观分析一下
宏观角度说,我们看到一个代理类生成了一个学生的代理,生成过程中用到了被代理类的类加载器、接口还有一个叫InvocationHandler()的东西。InvocationHandler()这个类的实现可以看出来就是这个类在被代理类调用方法的时候进行了处理。也就是说student调用方法的时候,处理器InvocationHandler(),会对每个方法进行拦截,然后检查这个方法是不是我需要代理的方法,是就做我该做的事情之后再调用原方法,不是的话直接调用原方法。这样做确实做到了动态代理。
JDK代码实现
那么JDK动态代理代码层面是怎么实现的呢?
- Proxy.newProxyInstance返回了这个代理类,那么先看一下Proxy的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);
}
}
重点看这三句:
Class<?> cl = getProxyClass0(loader, intfs);
final Constructor<?> cons = cl.getConstructor(constructorParams);
cons.newInstance(new Object[]{h});
根据源码注释,可以知道第一句生成了一个代理类,后两句使用这个代理类的构造函数生成了一个具体的对象,然后这个对象返回,也就是我们上面测试类中得到的代理类。而且这个构造函数是传入的参数是h,也就是调用处理器。
- getProxyClass0不是我们最终要找的,继续找,getProxyClass0
private static Class<?> getProxyClass0(ClassLoader loader,
Class<?>... interfaces) {
if (interfaces.length > 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);
}
从注释可以看出,如果这个代理类已经加载过了就从缓存中返回一份,如果没有就使用ProxyClassFactory去创建一份
- 那么我们去找ProxyClassFactory
/**
* 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
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());
}
}
}
byte[] proxyClassFile = ProxyGenerator.generateProxyClass( proxyName, interfaces, accessFlags);
这里生成了一个代理类字节码文件,将这字节码文件保存到本地,然后反编译就可以看到这个生成得代理类
- 查看生成的代理类中sayHello方法
public final String sayHello()
{
try
{
return (String)this.h.invoke(this, m3, null);
}
catch (Error|RuntimeException localError)
{
throw localError;
}
catch (Throwable localThrowable)
{
throw new UndeclaredThrowableException(localThrowable);
}
}
这里调用sayHello的时候,首先调用了h属性里的invoke方法,h其实是生成代理类父类Proxy的一个属性:
protected Proxy(InvocationHandler h) {
Objects.requireNonNull(h);
this.h = h;
}
那么一切都可以解释了: 生成的代理类中调用的方法都会使用h.invoke调用,传入参数和函数,让invoke决定怎么调用