zoukankan      html  css  js  c++  java
  • jdk的动态代理

    package com.jy.util;
    
    
    import sun.misc.ProxyGenerator;
    
    import java.io.FileOutputStream;
    import java.lang.reflect.InvocationHandler;
    import java.lang.reflect.Method;
    import java.lang.reflect.Proxy;
    
    public class Test {
    
        public static void main(String[] args) throws Exception {
            
            
            /*
            jdk的动态代理为什么只能是接口分析如下:
            将动态代理生成的字节码写入文件,其代理类是继承了原有的Proxy类,并实现implements了需要被代理的接口
            因为在java中是单继承,所以jdk的动态代理只能是接口
            */
            
            //UserService CompanyService 为需要生成代理的接口
            Class<?>[] clazz = {UserService.class, CompanyService.class};
            byte[] bytes = ProxyGenerator.generateProxyClass("$Proxy", clazz);
            FileOutputStream fos = new FileOutputStream("$Proxy.class");
            fos.write(bytes);
            fos.flush();
            fos.close();
            
            new Test().proxyTest();
    
        }
    
        private void proxyTest() {
            Class<?>[] interfaces = {IProxyTest.class};
            IProxyTest iProxyTest = (IProxyTest)Proxy.newProxyInstance(this.getClass().getClassLoader(), interfaces,new MyInvocationHandler(new IProxyTestImpl()));
            iProxyTest.run();
        }
        /**
            jdk的动态代理
        */
        class MyInvocationHandler implements InvocationHandler{
            private Object target;
            MyInvocationHandler(Object target){
                this.target = target;
            }
    
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                //动态代理前置处理
                System.out.println("前置处理");
                Object obj = method.invoke(target, args);
                //动态代理后置处理
                return obj;
            }
        }
    }
    人生没有彩排,每天都是现场直播!
  • 相关阅读:
    原型prototype
    this
    作用域、闭包、模块
    嵌入式面试资料
    一些嵌入式面试题目的集锦
    优先级反转
    struct和union的区别
    (转)typedef和#define的用法与区别
    const 和 #define区别
    白话经典算法系列之 快速排序 快速搞定
  • 原文地址:https://www.cnblogs.com/northern-light/p/10497639.html
Copyright © 2011-2022 走看看