代理模式是一种设计模式,提供了对目标对象额外的访问方式,即通过代理对象访问目标对象,这样可以在不修改原目标对象的前提下,提供额外的功能操作,扩展目标对象的功能。
java的代理模式: 静态代理、动态代理、CGLIB代理
1.静态代理
这种代理方式需要代理对象和目标对象实现一样的接口。
优点:可以在不修改目标对象的前提下扩展目标对象的功能。
缺点:
1.冗余。由于代理对象要实现与目标对象一致的接口,会产生过多的代理类。
2.不易维护。一旦接口增加方法,目标对象与代理对象都要进行修改。
例子:创建接口
package proxy;
public interface UserDao {
String getUserName();
}
package proxy;
public class UserDaoImpl implements UserDao {
public String getUserName() {
return "张三";
}
}
package proxy;
public class UserProxy implements UserDao {
private UserDao userDao;
public UserProxy(UserDaoImpl userdao){
this.userDao=userdao;
}
public String getUserName() {
return this.userDao.getUserName()+" 您好";
//return null;
}
}
package proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class DynamicProxy {
private Object object;
public DynamicProxy(Object target){
this.object=target;
}
public Object getProxy(){
Object o = Proxy.newProxyInstance(object.getClass().getClassLoader(), object.getClass().getInterfaces(), new InvocationHandler() {
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object returnValue = method.invoke(object, args);
return returnValue+" 动态代理";
}
});
return o;
}
}
package proxy;
public class TestDynamicProxy {
public static void main(String[] args) {
UserDao dao = new UserDaoImpl();
System.out.println(dao.getUserName());
DynamicProxy dynamicProxy = new DynamicProxy(dao);
UserDao userdao = (UserDao) dynamicProxy.getProxy();
System.out.println(userdao.getUserName());
}
}
@CallerSensitive
public static Object newProxyInstance(ClassLoader loader,
Class<?>[] interfaces,
InvocationHandler h)
throws IllegalArgumentException
{
Objects.requireNonNull(h);//如果InvocationHandler为空,直接出发空指针异常
final Class<?>[] intfs = interfaces.clone();//把接口复制一份当到intfs数组中
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())) { //判断是否是public的修饰符
AccessController.doPrivileged(new PrivilegedAction<Void>() {//获取上下文的doPrivileged方法
//可以限定权限范围
public Void run() {
cons.setAccessible(true);//设置为true 取消java的访问检查,
// 如果是false就执行java的访问检查
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);
}
}
private static Class<?> getProxyClass0(ClassLoader loader,
Class<?>... interfaces) {
if (interfaces.length > 65535) {//最多支持65535个类,类似linux系统的最大打开文件数量
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);
}
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<>());
//putIfAbsent 如果map中已经存在,那么后面的key相同也就不会覆盖原来的。
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);//@FunctionalInterface 函数式注解
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);
}
}
}
}
private final ReferenceQueue<K> refQueue
= new ReferenceQueue<>();
package proxy;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
import java.lang.reflect.Method;
public class ProxyFactory implements MethodInterceptor {
private Object target;//维护一个目标对象
public ProxyFactory(Object target) {
this.target = target;
}
//为目标对象生成代理对象
public Object getProxyInstance() {
//工具类
Enhancer en = new Enhancer();
//设置父类
en.setSuperclass(target.getClass());
//设置回调函数
en.setCallback(this);
//创建子类对象代理
return en.create();
}
public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
// 执行目标对象的方法
Object returnValue = method.invoke(target, objects);
return returnValue+"cglib";
}
}
-
静态代理实现较简单,由于代理对象要实现与目标对象一致的接口,会产生过多的代理类。还有就是不易维护,编译时产生class字节码文件,可以直接使用,效率高。
-
JDK动态代理需要目标对象实现业务接口,代理类只需实现InvocationHandler接口,通过反射代理方法,比较消耗系统性能,但可以减少代理类的数量,使用更灵活。
-
cglib代理无需实现接口,通过生成类字节码实现代理,比反射稍快,不存在性能问题,但cglib会继承目标对象,需要重写方法,所以目标对象不能为final类。
总结:
-
JDK的动态代理有一个限制,就是使用动态代理的对象必须实现一个或多个接口。 如果想代理没有实现接口的类,就可以使用CGLIB实现。
-
CGLIB是一个强大的高性能的代码生成包,它可以在运行期扩展Java类与实现Java接口。 它广泛的被许多AOP的框架使用,例如Spring AOP和dynaop,为他们提供方法的interception(拦截)。
-
CGLIB包的底层是通过使用一个小而快的字节码处理框架ASM,来转换字节码并生成新的类。 不鼓励直接使用ASM,因为它需要你对JVM内部结构包括class文件的格式和指令集都很熟悉。
cglib代理
jdk ReferenceQueue 类:引用队列,在检测到适当的可到达性更改后,垃圾回收器将已注册的引用对象添加到该队列中。java gc的回收机制。
proxyClassCache.get()方法
@CallerSensitive 注解的例子 有 bootstrap类加载器可以调用,Ext类加载器可以调用,通过此方法获取class时会跳过链路上所有的有@CallerSensitive注解的方法的类,直到遇到第一个未使用该注解的类
Proxy..newProxyInstance方法
测试类
静态代理是编译的时候已经生成class文件,动态代理不需要生成文件。
动态代理对象不需要实现接口,但是要求目标对象必须实现接口,否则不能使用动态代理。
这只是一个设计模式的运用。 2.动态代理
创建接口的代理类
创建接口实现类
3万+

被折叠的 条评论
为什么被折叠?



