一、静态代理
1.什么是静态代理
现有如下场景:张三是个厨师,做某一份美食分为以下三步:买食材、做菜、端桌,其中"买食材"和"端桌"是每个厨师都要干的事情,都相同,但是由于不同厨师的技艺不同,做菜方式不同。
1.1 普通实现方式
接下来用代码实现其功能,设想有一个"做饭"接口,其中有"买食材"、“做菜”、"端桌"三个方法,每一个厨师做这道美食都需要实现并重写此方法,如下:
做饭接口
public interface makeFood {
//买食材
void buyVegetables();
//做菜
void makeFood();
//端桌
void upTable();
}
张三做饭
public class zs implements makeFood{
@Override
public void buyVegetables() {
System.out.println("买食材");
}
@Override
public void makeFood() {
System.out.println("张三厨师做菜");
}
@Override
public void upTable() {
System.out.println("端桌");
}
}
李四做饭
public class ls implements makeFood{
@Override
public void buyVegetables() {
System.out.println("买食材");
}
@Override
public void makeFood() {
System.out.println("李四厨师做菜");
}
@Override
public void upTable() {
System.out.println("端桌");
}
}
测试类
class test{
public static void main(String[] args) {
//张三厨师做菜
zs zs = new zs();
zs.makeFood();
//李四厨师做菜
ls ls=new ls();
ls.makeFood();
}
}
如果是这样写代码的话,会发现冗余代码太多,其中"买食材"和"端桌"都是共同的,可以抽出来,那么就可以建立一个代理对象,代理对象中写入"买食材"和"端桌"方法,"做菜"方法可以使用传参的方式进行。
1.2 代理对象实现
现在需要一个代理对象,在这个代理对象中将"买食材"和"端桌"方法实现了,然后将相关的厨师作为参数传进"做菜"方法中,调用其方法,如下:
做饭接口
public interface makeFood {
//做菜
void makeFood();
}
代理对象
class foodProxy{
//买食材
public void buyVegetables() {
System.out.println("买食材");
}
//做菜
public void makeFood(makeFood people) {
people.makeFood();
}
//端桌
public void upTable() {
System.out.println("端桌");
}
}
张三厨师做饭(被代理对象)
class zs implements makeFood{
@Override
public void makeFood() {
System.out.println("张三厨师做菜");
}
}
李四厨师做饭(被代理对象)
class ls implements makeFood{
@Override
public void makeFood() {
System.out.println("李四厨师做菜");
}
}
测试类
class test{
public static void main(String[] args) {
//创建代理对象
foodProxy proxy=new foodProxy();
//张三厨师做菜
zs zs = new zs();
proxy.makeFood(zs);
//李四厨师做菜
ls ls=new ls();
proxy.makeFood(ls);
}
}
以上就是使用代理对象的全部代码,可以明显看出减少了代码的冗余,需要加某一个大厨,只需要重写"做菜"方法,其他的方法代理对象进行实现。
但是有没有发现一个问题?如果我不想做这道菜,想换一道菜怎么办?
那么菜的食材、端桌的方式也就发生了改变,接口和代理对象都要重新写,这样也很麻烦,那么就有了动态代理,详细请接着往下看。
二、动态代理
动态代理分为很多种,比如JDK动态代理、cglib等等,这块只讲JDK动态代理。
使用动态代理之后,用户就不用再写代理类,JDK底层会帮助用户自动生成这个类
1.与动态代理相关的两个类
java.lang.reflect.Proxy
是Java动态代理机制的主类,它提供了一个静态方法来作为一组接口动态地生成代理类及其对象。
newProxyInstance(ClassLoader loader,Class[] interfaces,InvocationHandler h)方法可用于生成代理类及代理对象。
java.lang.reflect.InvocationHandler
InvocationHandler进行实际业务增强的类,它自定义了一个invoke()方法,通常在该方法中实现对委托类的代理访问。
2. 动态代理实现
动态代理类
class myHandler implements InvocationHandler {
//被代理对象
private Object target;
public myHandler(){};
public myHandler(Object target){
this.target=target;
}
/**
* 获取动态代理对象
* @return
*/
public Object getProxyInstance(){
/**
* newProxyInstance()方法的参数
* ClassLoader loader:接口的类加载器
* Class<?> interfaces:接口的class
* InvocationHandler h:控制器
*/
return Proxy.newProxyInstance(target.getClass().getClassLoader(),target.getClass().getInterfaces(),this);
}
@Override
/**
* proxy:动态代理对象
* method:被代理对象当前正在执行中的业务方法
* args:被代理对象当前正在执行中方法的参数
*/
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//业务增强
System.out.println("买食材");
//代理对象的业务处理
//这块是通过反射来创建被代理对象
method.invoke(target,args);
//业务增强
System.out.println("端桌");
return null;
}
}
被代理对象类
class ww implements makeFood1{
@Override
public void makeFood() {
System.out.println("王五做菜");
}
}
class zl implements makeFood1{
@Override
public void makeFood() {
System.out.println("赵六做菜");
}
}
测试类
class test{
public static void main(String[] args) {
//创建王五大厨对象,即被代理对象
ww ww = new ww();
zl zl = new zl();
//创建赵六的动态代理对象
myHandler handler=new myHandler(zl);
//这块要用被代理对象所实现的接口进行接收
makeFood1 mk = (makeFood1)handler.getProxyInstance();
//调用王五的makeFood()方法
mk.makeFood();
System.out.println("==================================");
//创建王五的动态代理对象
myHandler handler1=new myHandler(ww);
makeFood1 mk1=(makeFood1)handler1.getProxyInstance();
//调用赵六的makeFood方法
mk1.makeFood();
}
}
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ASrxiwzP-1639118019819)(C:\Users\DRL\AppData\Roaming\Typora\typora-user-images\image-20211210095253535.png)]
3.动态代理源码分析
动态代理类
class myHandler implements InvocationHandler {
//被代理对象
private Object target;
public myHandler(){};
public myHandler(Object target){
this.target=target;
}
/**
* 获取动态代理对象
* @return
*/
public Object getProxyInstance(){
/**
* ClassLoader loader:接口的类加载器
* Class<?> interfaces:接口的class
* InvocationHandler h:控制器
*/
return Proxy.newProxyInstance(target.getClass().getClassLoader(),target.getClass().getInterfaces(),this);
}
@Override
/**
* proxy:动态代理对象
* method:被代理对象当前正在执行中的业务方法
* args:被代理对象当前正在执行中方法的参数
*/
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//业务增强
System.out.println("买食材");
//代理对象的业务处理
//这块是通过反射来创建被代理对象
method.invoke(target,args);
//业务增强
System.out.println("端桌");
return null;
}
}
分析Proxy.newInstance()方法
@CallerSensitive
//获取动态代理对象实例
public static Object newProxyInstance(ClassLoader loader,
Class<?>[] interfaces,
InvocationHandler h)
throws IllegalArgumentException
{
//判断InvocationHandler是否为null
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.
*/
//查找或生成代理类字节码文件
//下面会有对getProxyClass0()方法的分析
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);
}
}
//解密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
//上面的注释翻译过来就是:如果给定接口的代理类存在,那么会简单的返回副本
//如果没有,会通过ProxyClassFactory创建代理类
//下面会有proxyClassCache.get()方法的分析
return proxyClassCache.get(loader, interfaces);
}
//解密上面返回的方法
//key:加载器 parameter:代理类实现接口字节码文件数组
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<>());
if (oldValuesMap != null) {
valuesMap = oldValuesMap;
}
}
// create subKey and retrieve the possible Supplier<V> stored by that
// subKey from valuesMap
//创建动态代理对象
//创建动态代理对象,直接跳到下面,下面会有对这个方法的分析,subKeyFactory.apply()
Object subKey = Objects.requireNonNull(subKeyFactory.apply(key, parameter));
Supplier<V> supplier = valuesMap.get(subKey);
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);
}
}
}
}
//apply()方法是一个接口,找到Proxy类实现的方法,直接跳到215行
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.
*/
//创建代理对象实例,这个方法点进去之后就是native方法了,JVM就是使用这个来创建动态代理对象的
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());
}
}