JAVA 动态代理

参考文章:https://y4er.com/post/java-proxy/

一共讲两个,一个是静态代理,一个是动态代理!

静态代理

实现静态代理的前提:

1、代理类和被代理类实现了同一接口

2、被代理类需要实现具体继承接口中的方法

3、代理类调用的是具体类中的方法(也就是说代理类中需要接受一个被代理类的对象)

这里举的例子就是,供应商 - 微商 - 客户 之间的代理

供应商/微商的接口:

public interface Seller {
    public void toSell();
}

供应商的实现类:

public class NormalSeller implements Seller{

    @Override
    public void toSell() {
        System.out.println("我是卖鞋的!!!");
    }
}

微商类的实现(这里体现的就是代理类):

public class MicroSeller implements Seller {
    Seller normal = new NormalSeller();

    @Override
    public void toSell() {
        this.go();
        this.normal.toSell();
        this.againgo();
    }

    public void go(){
        System.out.println("瞧一瞧,看一看");
    }

    public void againgo(){
        System.out.println("要不继续看看?");
    }
}

这里Main如下:

public class Mymain {
    public static void main(String[] args){
        Seller testSeller = new MicroSeller();
        testSeller.toSell();
    }
}

那么以上是不是就通过静态代理,实现了微商类的代理类,因为我们在里面写了另外的两个方法goagaingo,通过这种静态代理模式,给了原本只有toSell方法就添加了两种方法,并且没有改变原来的类!

但是也有缺点:

1、要为每一个接口实现代理类,一旦接口增加方法,目标对象与代理对象都要维护。

这个缺点怎么理解?

比如现在又是一个,如果供应商需要回购不需要的鞋子的话,在接口中就需要添加一个buy的方法,那么被代理需要去实现,然后代理类也需要进行调用,导致了两个类都需要进行维护!

动态代理

动态代理的话,就可以帮助我们解决上面的问题!

动态代理和静态代理的唯一区别就在于:动态代理是动态生成的,省去为接口实现代理类的操作。

要使用动态代理的话,只需要将被代理类继承InvocationHandler接口,然后实现其中的方法invoke即可!

那么静态代理中的被代理类实现动态代理:

这里写的时候有个变动,就是 之前说的代理类中需要接受一个被代理类的对象,现在这个被代理类的对象就作为代理类的构造函数的参数传入!

供应商/微商的接口:

public class NormalSeller implements Seller{

    @Override
    public void toSell() {
        System.out.println("我是卖鞋的!!!");
    }
}

供应商的实现类:

public class NormalSeller implements Seller{

    @Override
    public void toSell() {
        System.out.println("我是卖鞋的!!!");
    }
}

微商实现的类:

public class MicroSeller implements InvocationHandler {
    Object normal;

    public MicroSeller(Object normal){
        this.normal = normal;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("瞧一瞧,看一看!!!");

        if(method.getName().equals("toSell")){
            try {
                method.invoke(this.normal, args);
//                System.out.println("this is my toSell method!!!");
            }catch (Exception e){
                System.out.println(e);
                return null;
            }
        }
        System.out.println("要不继续看看???");
        return null;
    }
}
public class MyMain {
    public static void main(String[] args){
        Seller normal = new NormalSeller();
        InvocationHandler invocationHandler = new MicroSeller(normal);
        
        Seller microSeller = (Seller)Proxy.newProxyInstance(
                Seller.class.getClassLoader(),
                new Class[]{Seller.class},
                invocationHandler);

        microSeller.toSell();
    }
}

结果图如下:

继续讲,通过动态代理就可以方便的进行代理,就是将被代理类继续接口InvocationHandler,然后去实现InvocationHandler接口中的invoke方法,在invoke方法中进行我们要想代理的东西即可!

Proxy.newProxyInstance流程

那么继续思考,Proxy.newProxyInstance到底是怎么实现的,它为什么可以帮助我们实现自己想要实现的代理方法、语句等?

跟进去继续看newProxyInstance的源码实现(讲重点,主要自己看的太吃力了):

   public static Object newProxyInstance(ClassLoader loader,
                                          Class<?>[] interfaces,
                                          InvocationHandler h)
        throws IllegalArgumentException
    {
        Objects.requireNonNull(h); //判断InvocationHandler实例h存在不存在,不存在则直接抛出异常

        final Class<?>[] intfs = interfaces.clone(); //撒子玩意,盲猜 返回了Interface的class实例
        final SecurityManager sm = System.getSecurityManager(); //得到系统管理器的实例
        if (sm != null) { //判断系统管理器实例是否获得
            checkProxyAccess(Reflection.getCallerClass(), loader, intfs); //检查权限,看了下getProxyClass0里面的注释,如果调用getProxyClass0方法就必须判断权限checkProxyAccess
        }

        /*
         * Look up or generate the designated proxy class.
         */
        Class<?> cl = getProxyClass0(loader, intfs); //获取代理类,里面是return proxyClassCache.get(loader, interfaces); ,这里注释有说明,
//如果你传入的loader定义的代理类有实现指定的接口的话,就通过WeakCache类的缓存中返回一个代理类,如果不是,就通过ProxyClassFactory来生成一个代理类

        /*
         * Invoke its constructor with the designated invocation handler.
         */
        try {
            if (sm != null) {
                checkNewProxyPermission(Reflection.getCallerClass(), cl); //大概就是权限检测
            }

            final Constructor<?> cons = cl.getConstructor(constructorParams); //获取实现InvocationHandler接口的类的构造函数
            final InvocationHandler ih = h; //接受了参数InvocationHandler h
            if (!Modifier.isPublic(cl.getModifiers())) { //判断该类的修饰符是否为public属性
                AccessController.doPrivileged(new PrivilegedAction<Void>() { //如果不是的话则改为public
                    public Void run() {
                        cons.setAccessible(true);
                        return null;
                    }
                });
            }
            return cons.newInstance(new Object[]{h}); //通过cons构造器创建一个对应的Class实例的对象
        } 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中的方法:

如下显示,通过注释可以知道,如果传入的加载器定义的代理类实现给定的接口存在,这将简单地返回缓存副本,否则就使用ProxyClassFactory去生成这个代理类

    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);
    }

ProxyClassFactory为如下:

private static final class ProxyClassFactory
    implements BiFunction<ClassLoader, Class<?>[], Class<?>>
{
    // prefix for all proxy class names
    private static final String proxyClassNamePrefix = "$Proxy"; //代理类对象的前缀名 $Proxy


    // next number to use for generation of unique proxy class names 
    private static final AtomicLong nextUniqueNumber = new AtomicLong(); //用于生成唯一代理类名的下一个编号


    @Override
    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); //通过指定loader加载器生成指定类,如果没有找到指定的类则抛出异常
            } catch (ClassNotFoundException e) {
            }
            if (interfaceClass != intf) { //如果加载的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 + "."; // "com.sun.proxy." 字符串进行拼接
        }

        /*
         * Choose a name for the proxy class to generate.
         */
        long num = nextUniqueNumber.getAndIncrement();
        String proxyName = proxyPkg + proxyClassNamePrefix + num; // 拼接要生成代理类的名称, com.sun.proxy.$Proxy0/1/2/3

        /*
         * Generate the specified proxy class.
         */
        byte[] proxyClassFile = ProxyGenerator.generateProxyClass(proxyName, interfaces, accessFlags); //获取要生成类class的字节码

        try {
            return defineClass0(loader, proxyName, proxyClassFile, 0, proxyClassFile.length); //通过反射defineClass0生成一个指定的Class类实例
        } 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());
        }
    }
}

运行如下代码:

public class MyMain {
    public static void main(String[] args){
        Seller normal = new NormalSeller();
        InvocationHandler invocationHandler = new MicroSeller(normal);

        Seller microSeller = (Seller)Proxy.newProxyInstance(
                Seller.class.getClassLoader(),
                new Class[]{Seller.class},
                invocationHandler);


        microSeller.toSell();

        System.out.println(microSeller.getClass().getName());

    }
}

最终获取的类名为如下显示:

那么其实也就是Proxy.newInstance()反射动态生成了一个对应的代理类返回,并且该类的名称还是com.sun.proxy.$Proxy0/1/2/3递增的!

原文地址:https://www.cnblogs.com/zpchcbd/p/13368185.html