基本介绍:
基本介绍:
静态代理在使用时,需要定义接口或者父类,被代理对象(即目标对象)与代理对象一 起实现相同的接口或者是继承相同父类
接口:
/**
* 接口
*/
public interface ITeacherDao {
/**
* 授课方式
*/
public void teach();
}
接口实现:
public class TeacherDao implements ITeacherDao{
@Override
public void teach() {
System.out.println("开始授课教学....");
}
}
静态代理:
public class TeacherDaoProxy implements ITeacherDao{
private ITeacherDao proxy;
public TeacherDaoProxy(ITeacherDao proxy) {
this.proxy = proxy;
}
@Override
public void teach() {
System.out.println("增强教学中....");
proxy.teach();
System.out.println("增强教学结束..");
}
public static void main(String[] args) {
// 创建目标对象(被代理对象)
TeacherDao teacherDao = new TeacherDao();
// 创建代理对象,同时将被代理对象传递给代理对象
TeacherDaoProxy proxy = new TeacherDaoProxy(teacherDao);
proxy.teach();
}
}
优点:
在不修改目标对象的功能前提下,能通过代理对象对目标功能扩展
缺点:
基本介绍:
JDK 生成代理对象的 API:
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class ProxyFactory {
// 维护一个目标对象, Object
private Object target;
// 构造器, 对 target 进行初始化
public ProxyFactory(Object target) {
this.target = target;
}
// 生成代理对象
public Object getProxyInstance(){
//1. ClassLoader loader : 指定当前目标对象使用的类加载器, 获取加载器的方法固定
//2. Class>[] interfaces: 目标对象实现的接口类型,使用泛型方法确认类型
//3. InvocationHandler h : 事情处理,执行目标对象的方法时,会触发事情处理器方法, 会把当前执行的目标对象方法作为参数传入
return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("JDK 代理开始...");
Object proxyObj = method.invoke(target, args);
System.out.println("JDK 代理结束...");
return proxyObj;
}
});
}
public static void main(String[] args) {
TeacherDao techerDao = new TeacherDao();
ProxyFactory proxyFactory = new ProxyFactory(techerDao);
ITeacherDao proxy = (ITeacherDao) proxyFactory.getProxyInstance();
proxy.teach();
}
}
源码分析:
newProxyInstance方法:
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) {
// Reflection.getCallerClass() 返回调用该方法的方法的调用类
// 访问权限以及类加载器权限等检查
checkProxyAccess(Reflection.getCallerClass(), loader, intfs);
}
// 查找或者生成指定代理类
Class> cl = getProxyClass0(loader, intfs);
try {
if (sm != null) {
checkNewProxyPermission(Reflection.getCallerClass(), cl);
}
// 获取代理类的构造方法对象
// constructorParams 是类常量,作为代理类构造函数的参数类型
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");
}
// 如果缓存有代理类直接返回,否则将由类工厂 ProxyClassFactory 创建代理类
return proxyClassCache.get(loader, interfaces);
}
get 方法:
public V get(K key, P parameter) {
// 检查指定类型的对象引用不为空
Objects.requireNonNull(parameter);
// 清空已经被 GC 回收的弱引用
expungeStaleEntries();
// 将 classLoader 包装成 CacheKey,作为一级缓存的 KEY
Object cacheKey = CacheKey.valueOf(key, refQueue);
// 获取二级缓存
ConcurrentMap
apply 方法:
@Override
public Class> apply(ClassLoader loader, Class>[] interfaces) {
Map, Boolean> interfaceSet = new IdentityHashMap<>(interfaces.length);
for (Class> intf : interfaces) {
// 验证指定的类加载器(Loader) 加载接口所得到的 Class 对象(interfaceClass) 是否与 intf 对象相同
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");
}
// 验证 Class 对象是不是接口
if (!interfaceClass.isInterface()) {
throw new IllegalArgumentException(
interfaceClass.getName() + " is not an interface");
}
// 验证接口是否重复
if (interfaceSet.put(interfaceClass, Boolean.TRUE) != null) {
throw new IllegalArgumentException(
"repeated interface: " + interfaceClass.getName());
}
}
// 声明代理类所在包
String proxyPkg = null;
int accessFlags = Modifier.PUBLIC | Modifier.FINAL;
// 验证所有非公共的接口在同一包内
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) {
// 如果都是public 接口,那么生成的代理类就在com.sun.proxy 包下
// 如果报文件找不到,则在项目中创建 com.sun.proxy 路径
proxyPkg = ReflectUtil.PROXY_PACKAGE + ".";
}
long num = nextUniqueNumber.getAndIncrement();
// 代理类的完全限定类名 如 com.sun.proxy.$Proxy0.class
String proxyName = proxyPkg + proxyClassNamePrefix + num;
// 生成代理类的字节码数组
byte[] proxyClassFile = ProxyGenerator.generateProxyClass(
proxyName, interfaces, accessFlags);
// 生成 class
try {
return defineClass0(loader, proxyName,
proxyClassFile, 0, proxyClassFile.length);
} catch (ClassFormatError e) {
throw new IllegalArgumentException(e.toString());
}
}
}
动态代理为什么要有接口:
通过父类 Proxy 的构造方法,保存了创建代理对象过程中传进来的 InvocationHandler 的实例,使用 protected 修饰保证了它可以在子类中被访问和使用。但是同时,因为 Java 是单继承的,因此在代理类 $Proxy0 继承了 Proxy 后,其只能通过实现目标接口的方式来实现方法的扩展,达到我们增强目标方法逻辑的目的
流程图:
基本介绍:
代理实现:
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;
import java.lang.reflect.Method;
public class ProxyFactory implements MethodInterceptor {
// 维护一个目标对象
private Object target;
// 构造器,传一个被代理的对象
public ProxyFactory(Object target){
this.target = target;
}
// 返回一个代理对象: 是 target 对象的代理对象
public Object getProxyInstance(){
// 创建一个工具类,增强器
Enhancer enhancer = new Enhancer();
// 设置父类
enhancer.setSuperclass(target.getClass());
// 设置回调函数
enhancer.setCallback(this);
// 创建子类对象,即代理对象
return enhancer.create();
}
@Override
public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
System.out.println("Cglib 代理模式...开始");
Object obj = method.invoke(target, objects);
System.out.println("Cglib 代理模式...结束");
return obj;
}
public static void main(String[] args) {
TeacherDao teacherDao = new TeacherDao();
ProxyFactory proxyFactory = new ProxyFactory(teacherDao);
TeacherDao proxy = (TeacherDao) proxyFactory.getProxyInstance();
proxy.teach();
}
}
源码分析:
createHelper
private Object createHelper() {
this.preValidate();
// 生成了一个 EnhancerKey 代理对象,该代理对象里面保存了用户所设置的代理信息
// 缓存到 LoadingCache
Object key = KEY_FACTORY.newInstance(this.superclass != null ? this.superclass.getName() : null, ReflectUtils.getNames(this.interfaces), this.filter == ALL_ZERO ? null : new WeakCacheKey(this.filter), this.callbackTypes, this.useFactory, this.interceptDuringConstruction, this.serialVersionUID);
this.currentKey = key;
// 去创建代理对象,避免重复 create
Object result = super.create(key);
return result;
}
create
protected Object create(Object key) {
try {
ClassLoader loader = this.getClassLoader();
Map cache = CACHE;
AbstractClassGenerator.ClassLoaderData data = (AbstractClassGenerator.ClassLoaderData)cache.get(loader);
if (data == null) {
Class var5 = AbstractClassGenerator.class;
synchronized(AbstractClassGenerator.class) {
cache = CACHE;
data = (AbstractClassGenerator.ClassLoaderData)cache.get(loader);
if (data == null) {
Map newCache = new WeakHashMap(cache);
// 构造方法中会生成一个代理类的 lambda 表达式
data = new AbstractClassGenerator.ClassLoaderData(loader);
newCache.put(loader, data);
CACHE = newCache;
}
}
}
this.key = key;
// 利用 ClassLoaderData 拿到代理类, ClassLoaderData 中有一个 generatedClasses 用来缓存生成好的代理类
Object obj = data.get(this, this.getUseCache());
// 调用代理类的构造发那个发生成一个代理对象
return obj instanceof Class ? this.firstInstance((Class)obj) : this.nextInstance(obj);
} catch (Error | RuntimeException var9) {
throw var9;
} catch (Exception var10) {
throw new CodeGenerationException(var10);
}
}
createUsingReflection
private Object createUsingReflection(Class type) {
// 设置 callbacks 到代理类中
setThreadCallbacks(type, this.callbacks);
Object var2;
try {
if (this.argumentTypes == null) {
var2 = ReflectUtils.newInstance(type);
return var2;
}
var2 = ReflectUtils.newInstance(type, this.argumentTypes, this.arguments);
} finally {
setThreadCallbacks(type, (Callback[])null);
}
return var2;
}
setCallbacksHelper
// 设置 ThreadLocal CGLIB$SET_THREAD_CALLBACKS 属性
private static void setThreadCallbacks(Class type, Callback[] callbacks) {
setCallbacksHelper(type, callbacks, "CGLIB$SET_THREAD_CALLBACKS");
}
private static void setCallbacksHelper(Class type, Callback[] callbacks, String methodName) {
try {
Method setter = getCallbacksSetter(type, methodName);
setter.invoke((Object)null, callbacks);
} catch (NoSuchMethodException var4) {
throw new IllegalArgumentException(type + " is not an enhanced class");
} catch (IllegalAccessException var5) {
throw new CodeGenerationException(var5);
} catch (InvocationTargetException var6) {
throw new CodeGenerationException(var6);
}
}
generate
protected Class generate(ClassLoaderData data) {
this.validate();
// 生成类的前缀名字
if (this.superclass != null) {
this.setNamePrefix(this.superclass.getName());
} else if (this.interfaces != null) {
this.setNamePrefix(this.interfaces[ReflectUtils.findPackageProtected(this.interfaces)].getName());
}
return super.generate(data);
}
protected Class generate(AbstractClassGenerator.ClassLoaderData data) {
Object save = CURRENT.get();
CURRENT.set(this);
Class var8;
try {
ClassLoader classLoader = data.getClassLoader();
if (classLoader == null) {
throw new IllegalStateException("ClassLoader is null while trying to define class " + this.getClassName() + ". It seems that the loader has been expired from a weak reference somehow. Please file an issue at cglib's issue tracker.");
}
String className;
synchronized(classLoader) {
className = this.generateClassName(data.getUniqueNamePredicate());
data.reserveName(className);
this.setClassName(className);
}
Class gen;
if (this.attemptLoad) {
try {
gen = classLoader.loadClass(this.getClassName());
Class var23 = gen;
return var23;
} catch (ClassNotFoundException var19) {
}
}
byte[] b = this.strategy.generate(this);
className = ClassNameReader.getClassName(new ClassReader(b));
ProtectionDomain protectionDomain = this.getProtectionDomain();
synchronized(classLoader) {
gen = ReflectUtils.defineClass(className, b, classLoader, protectionDomain, this.contextClass);
}
var8 = gen;
} catch (Error | RuntimeException var20) {
throw var20;
} catch (Exception var21) {
throw new CodeGenerationException(var21);
} finally {
CURRENT.set(save);
}
return var8;
}