1.创建被代理的接口和类;
2.创建InvocationHandler接口的实现类,在invoke方法中实现代理逻辑;
3.通过Proxy的静态方法newProxyInstance( ClassLoader classLoader, Class[] interfaces, InvocationHandler invocationHandler )
创建一个代理对象,其中classLoader为被代理类的加载器,interfaces为被代理的接口,invocationHandler 表示步骤二中的
InvocationHandler接口的实现类;
4.对代理对象的使用;
接口:
package com.spring.aspect;
public interface TestService {
void test();
}
实现类
package com.spring.aspect;
public class TestServiceImpl implements TestService {
@Override
public void test() {
System.out.println("test");
}
}
代理:
package com.spring.aspect;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
public class TestInvocationHandler implements InvocationHandler{
//目标对象
private Object target;
//构造方法
public TestInvocationHandler(Object target) {
super();
this.target = target;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// TODO Auto-generated method stub
System.out.println("before test");
method.invoke(target,args);
System.out.println("after test");
return null;
}
}
测试方法:
package com.spring.aspect;
import java.lang.reflect.Proxy;
public class ProxyTest {
public static void main(String[] args) {
// 需要被代理的对象
TestService tmp = new TestServiceImpl();
//代理的处理器
TestInvocationHandler t = new TestInvocationHandler(tmp);
//通过Proxy的newProxyInstance方法创建代理对象,
TestService res = (TestService) Proxy.newProxyInstance(tmp.getClass().getClassLoader(), tmp.getClass().getInterfaces(), t);
res.test();
}
}
主要是生成代理类的方法: TestService res = (TestService) Proxy.newProxyInstance(tmp.getClass().getClassLoader(), tmp.getClass().getInterfaces(), t);
通过源码获取:
@CallerSensitive
public static Object newProxyInstance(ClassLoader loader,
Class>[] interfaces,
InvocationHandler h)
throws IllegalArgumentException
{
// 校验h是否为空
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);
}
//得到代理类对象的构造函数,这个构造函数的参数由constructorParams指定
//参数constructorParames为常量值:private static final Class>[] constructorParams = { InvocationHandler.class };
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);
}
}
其中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);
}
从一个缓存中获取代理类
对WeakCache
具体实现代码如下:
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
// create subKey and retrieve the possible Supplier
// subKey from valuesMap
Object subKey = Objects.requireNonNull(subKeyFactory.apply(key, parameter));//apply具体方法如下
Supplier
Factory factory = null;
while (true) {
if (supplier != null) {//缓存里有supplier ,直接通过get方法返回代理类对象
// supplier might be a Factory or a CacheValue
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对象,把subKey放在Factory对象中
factory = new Factory(key, parameter, subKey, valuesMap);
}
if (supplier == null) {//放入valuesMap,并将factory值赋予supplier
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);
}
}
}
}
根据加载器和接口,根据接口个数生成对应的sub-key
从以上可以得出,具体获取代理类的方法在supplier.get();中实现,并且supplier为代码中的Factory
Factory为weakCache的一个内部类具体get方法如下:
@Override
public synchronized V get() { // serialize access
// re-check进行再次校验
Supplier
if (supplier != this) {
// something changed while we were waiting:
// might be that we were replaced by a CacheValue
// or were removed because of failure ->
// return null to signal WeakCache.get() to retry
// the loop
return null;
}
// else still us (supplier == this)
// create new value生成value并返回结果
V value = null;
try {
value = Objects.requireNonNull(valueFactory.apply(key, parameter));
} finally {
if (value == null) { // remove us on failure
valuesMap.remove(subKey, this);
}
}
// the only path to reach here is with non-null value
assert value != null;
// wrap value with CacheValue (WeakReference)
CacheValue
// put into reverseMap
reverseMap.put(cacheValue, Boolean.TRUE);
// try replacing us with CacheValue (this should always succeed)
if (!valuesMap.replace(subKey, this, cacheValue)) {
throw new AssertionError("Should not reach here");
}
// successfully replaced us with new CacheValue -> return the value
// wrapped by it
return value;
}
}
从上面代码可以知道具体的实现方法就是valueFactory.apply(key, parameter),这里的valueFactory就是Proxy的静态内部类ProxyClassFactory
具体apply方法如下:
@Override
public Class> apply(ClassLoader loader, Class>[] interfaces) {
Map
for (Class> intf : interfaces) {
/*
* Verify that the class loader resolves the name of this
* interface to the same Class object.
*/
Class> interfaceClass = null;
try {//加载器和接口生成对应的类,false代表不实例
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;//获取代理名com.sun.proxy.$Proxy0 当num为0时
/*
* Generate the specified proxy class. 生成代理类的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());
}
}
那么生成的class文件是怎么样的呢?
package com.sun.proxy;
import com.spring.aspect.TestService ;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.lang.reflect.UndeclaredThrowableException;
//继承了Proxy类,实现了TestService 接口
public final class $Proxy0 extends Proxy implements TestService {
private static Method m1;//TestSetvice中的方法
private static Method m2;
private static Method m3;
private static Method m0;
//构造方法,直接调用了父类,也就是Proxy的构造方法,参数paramInvocationHandler就是我们的TestInvocationHandler实例化对象handler
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);
}
}
//实现了test
public final void test()
throws {
try
{
// 这里的h就是我们的TestInvocationHandler实例化对象handler,原因在下方解释。
// 这里直接调用了TestInvocationHandler的invoke方法 实现aop
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);
}
}
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);
}
}
//静态代码块,做初始化操作
static
{
try
{
m1 = Class.forName("java.lang.Object").getMethod("equals", new Class[] { Class.forName("java.lang.Object") });
//通过反射,获取sayGoodBye方法对象实例
m3 = Class.forName("com.spring.aspect.TestService").getMethod("test", null);
m2 = Class.forName("java.lang.Object").getMethod("toString", new Class[0]);
m0 = Class.forName("java.lang.Object").getMethod("hashCode", new Class[0]);
return;
}
catch (NoSuchMethodException localNoSuchMethodException)
{
throw new NoSuchMethodError(localNoSuchMethodException.getMessage());
}
catch (ClassNotFoundException localClassNotFoundException)
{
throw new NoClassDefFoundError(localClassNotFoundException.getMessage());
}
}
}
故代理类调用了test方法后就是调用了
即调用了自定义invocationHandler中的invoke方法
其中m3方法就是通过反射获取的
故以上就是jdk动态代理的实现原理