Spring AOP(一):jdk动态代理
2021-01-20 23:12
标签:require packages over 执行 字节流 design 名称 auth proxy JDK动态代理是代理模式的一种实现方式。只能代理接口类,因为Java语言为单继承语言,所以只能以实现接口的方式构建代理对象。 代理类继承了Proxy类并且实现了要代理的接口,由于java不支持多继承,所以JDK动态代理不能代理类。 重写了equals、hashCode、toString。 有一个静态代码块,通过反射或者代理类的所有方法。 通过invoke执行代理类中的目标方法doSomething。 接口,实现类保持不变。 Spring AOP(一):jdk动态代理 标签:require packages over 执行 字节流 design 名称 auth proxy 原文地址:https://www.cnblogs.com/chinda/p/12898890.htmlJDK动态代理
简单示例
package com.chinda.aop;
/**
* 被代理接口
*
* @author Wang Chinda
* @date 2020/5/16
* @see
* @since 1.0
*/
public interface Subject {
void doSomething();
}
package com.chinda.aop;
/**
* 真正的对象
*
* @author Wang Chinda
* @date 2020/5/16
* @see
* @since 1.0
*/
public class RealSubject implements Subject {
@Override
public void doSomething() {
System.out.println("realSubject to do something!");
}
}
import com.chinda.aop.RealSubject;
import com.chinda.aop.Subject;
import org.junit.Test;
import java.lang.reflect.Proxy;
/**
* @author Wang Chinda
* @date 2020/5/16
* @see
* @since 1.0
*/
public class JdkDynamicProxyTest {
@Test
public void test() {
// 保存生成的代理类的字节码文件, 方便查看(可省略)
System.getProperties().put("sun.misc.ProxyGenerator.saveGeneratedFiles", "true");
RealSubject realSubject = new RealSubject();
Subject subjectProxy = (Subject) Proxy.newProxyInstance(realSubject.getClass().getClassLoader(), realSubject.getClass().getInterfaces(), (proxy, method, args) -> {
System.out.println("before to do something!");
Object result = method.invoke(realSubject, args);
System.out.println("after to do something!");
return result;
});
subjectProxy.doSomething();
}
}
控制台输出
before to do something!
realSubject to do something!
after to do something!
注意: 保存代理类字节码文件需要配置jvm参数:-Dsun.misc.ProxyGenerator.saveGeneratedFiles=true
代理类字节码文件反编译
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
package com.sun.proxy;
import com.chinda.aop.Subject;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.lang.reflect.UndeclaredThrowableException;
public final class $Proxy4 extends Proxy implements Subject {
private static Method m1;
private static Method m3;
private static Method m2;
private static Method m0;
public $Proxy4(InvocationHandler var1) throws {
super(var1);
}
public final boolean equals(Object var1) throws {
try {
return (Boolean)super.h.invoke(this, m1, new Object[]{var1});
} catch (RuntimeException | Error var3) {
throw var3;
} catch (Throwable var4) {
throw new UndeclaredThrowableException(var4);
}
}
public final void doSomething() throws {
try {
super.h.invoke(this, m3, (Object[])null);
} catch (RuntimeException | Error var2) {
throw var2;
} catch (Throwable var3) {
throw new UndeclaredThrowableException(var3);
}
}
public final String toString() throws {
try {
return (String)super.h.invoke(this, m2, (Object[])null);
} catch (RuntimeException | Error var2) {
throw var2;
} catch (Throwable var3) {
throw new UndeclaredThrowableException(var3);
}
}
public final int hashCode() throws {
try {
return (Integer)super.h.invoke(this, m0, (Object[])null);
} catch (RuntimeException | Error var2) {
throw var2;
} catch (Throwable var3) {
throw new UndeclaredThrowableException(var3);
}
}
static {
try {
m1 = Class.forName("java.lang.Object").getMethod("equals", Class.forName("java.lang.Object"));
m3 = Class.forName("com.chinda.aop.Subject").getMethod("doSomething");
m2 = Class.forName("java.lang.Object").getMethod("toString");
m0 = Class.forName("java.lang.Object").getMethod("hashCode");
} catch (NoSuchMethodException var2) {
throw new NoSuchMethodError(var2.getMessage());
} catch (ClassNotFoundException var3) {
throw new NoClassDefFoundError(var3.getMessage());
}
}
}
源码分析
jdk版本
$ java -version
java version "1.8.0_162"
Java(TM) SE Runtime Environment (build 1.8.0_162-b12)
Java HotSpot(TM) 64-Bit Server VM (build 25.162-b12, mixed mode)
粗略流程
查看
Proxy.newProxyInstance
@CallerSensitive
public static Object newProxyInstance(ClassLoader loader,
Class>[] interfaces,
InvocationHandler h)
throws IllegalArgumentException
{
// 检查调用控制器是否为null, 若是null抛异常
Objects.requireNonNull(h);
// 克隆接口Class[]
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);
/*
* 使用自定义的InvocationHandler构造代理对象实例
*/
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
查看创建代理类字节码文件
getProxyClass0
private static Class> getProxyClass0(ClassLoader loader,
Class>... interfaces) {
// 判断接口数是否超过65535
if (interfaces.length > 65535) {
throw new IllegalArgumentException("interface limit exceeded");
}
// 如果缓存中已经存在相应接口的代理类,直接返回;否则,使用ProxyClassFactory创建代理类
return proxyClassCache.get(loader, interfaces);
}
查看
proxyClassCache.get(loader, interfaces)
// 创建代理类
Object subKey = Objects.requireNonNull(subKeyFactory.apply(key, parameter));
查看
ProxyClassFactory
private static final class ProxyClassFactory
implements BiFunction
封装上述示例
引入依赖包
创建动态代理功能类
package com.chinda.aop;
import lombok.AllArgsConstructor;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
/**
* @author Wang Chinda
* @date 2020/5/16
* @see
* @since 1.0
*/
@AllArgsConstructor
public class JdkDynamicProxy implements InvocationHandler {
/**
* 被代理类
*/
private Object target;
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object result = null;
try {
System.out.println("before to do something!");
result = method.invoke(target, args);
System.out.println("return to do something! result: " + result);
} catch (Exception e) {
e.printStackTrace();
System.out.println("exception to do something");
} finally {
System.out.println("after to do something!");
}
return result;
}
}
创建测试方法
import com.chinda.aop.JdkDynamicProxy;
import com.chinda.aop.RealSubject;
import com.chinda.aop.Subject;
import org.junit.Test;
import java.lang.reflect.Proxy;
/**
* @author Wang Chinda
* @date 2020/5/16
* @see
* @since 1.0
*/
public class JdkDynamicProxyTest {
@Test
public void test2() {
RealSubject realSubject = new RealSubject();
Subject subjectProxy = (Subject) Proxy.newProxyInstance(realSubject.getClass().getClassLoader(), realSubject.getClass().getInterfaces(), new JdkDynamicProxy(realSubject));
subjectProxy.doSomething();
}
}
继续封装
创建获取代理接口
package com.chinda.aop;
/**
* @author Wang Chinda
* @date 2020/5/16
* @see
* @since 1.0
*/
public interface AopProxy {
/**
* 获取代理类
* @return
*/
Object getProxy();
}
修改动态代理功能类
package com.chinda.aop;
import lombok.AllArgsConstructor;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
/**
* @author Wang Chinda
* @date 2020/5/16
* @see
* @since 1.0
*/
@AllArgsConstructor
public class JdkDynamicProxy implements AopProxy, InvocationHandler {
/**
* 被代理类
*/
private Object target;
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object result = null;
try {
System.out.println("before to do something!");
result = method.invoke(target, args);
System.out.println("return to do something! result: " + result);
} catch (Exception e) {
e.printStackTrace();
System.out.println("exception to do something");
} finally {
System.out.println("after to do something!");
}
return result;
}
@Override
public Object getProxy() {
return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), this);
}
}
创建测试方法
import com.chinda.aop.JdkDynamicProxy;
import com.chinda.aop.RealSubject;
import com.chinda.aop.Subject;
import org.junit.Test;
import java.lang.reflect.Proxy;
/**
* @author Wang Chinda
* @date 2020/5/16
* @see
* @since 1.0
*/
public class JdkDynamicProxyTest {
@Test
public void test3() {
Subject subjectProxy = (Subject) new JdkDynamicProxy(new RealSubject()).getProxy();
subjectProxy.doSomething();
}
}
上一篇:C#反射与特性(一):反射基础
文章标题:Spring AOP(一):jdk动态代理
文章链接:http://soscw.com/index.php/essay/44741.html