jdk生成动态代理类


Proxy

static Class<?>getProxyClass(ClassLoader loader, Class<?>... interfaces) 


创建动态类及查看其方法列表信息

ProxyTest.java

public class ProxyTest {
    public static void main(String[] args) {
        //这是一个字节码
        Class clazzProxy1 = Proxy.getProxyClass(Collection.class.getClassLoader(), Collection.class);
//        System.out.println(clazzProxy1.getName());
        
        System.out.println("begin construtcor list ================================================ ");
        Constructor[] constructors = clazzProxy1.getConstructors();
        for (Constructor constructor : constructors) {
            String conName = constructor.getName();
            StringBuilder stringBuilder = new StringBuilder(conName);
            stringBuilder.append("(");
            Class[] clazzParams = constructor.getParameterTypes();
            for (Class clazzParam : clazzParams) {
                stringBuilder.append(clazzParam.getName()).append('|');
            }
            if (clazzParams != null && clazzParams.length != 0) {
                stringBuilder.deleteCharAt(stringBuilder.length()-1);
            }
            stringBuilder.append(")");
            System.out.println(stringBuilder.toString());
        }
        
        System.out.println("end construtcor list ================================================ ");
//        System.out.println(clazzProxy1.getName());
        
        
        System.out.println("begin methods list ================================================ ");
        Method[] methods = clazzProxy1.getMethods();
        for (Method method : methods) {
            String conName = method.getName();
            StringBuilder stringBuilder = new StringBuilder(conName);
            stringBuilder.append("(");
            Class[] clazzParams = method.getParameterTypes();
            for (Class clazzParam : clazzParams) {
                stringBuilder.append(clazzParam.getName()).append('|');
            }
            if (clazzParams != null && clazzParams.length != 0) {
                stringBuilder.deleteCharAt(stringBuilder.length()-1);
            }
            stringBuilder.append(")");
            System.out.println(stringBuilder.toString());
        }
        
        System.out.println("end methods list ================================================ ");
        
    }
}


创建动态类的实例对象及调用其方法


System.out.println("begin create instanse list ================================================ ");
        
        Constructor constructor = clazzProxy1.getConstructor(InvocationHandler.class);
        class myInvocationHandler1 implements InvocationHandler {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args)
                    throws Throwable {
                // TODO Auto-generated method stub
                return null;
            }
        };
        Collection proxy1 = (Collection)constructor.newInstance(new myInvocationHandler1());
        
        Collection proxy2 = (Collection)constructor.newInstance(new InvocationHandler(){
            @Override
            public Object invoke(Object proxy, Method method, Object[] args)
                    throws Throwable {
                // TODO Auto-generated method stub
                return null;
            }
        });
        
        Collection proxy3 = (Collection)Proxy.newProxyInstance(
                Collection.class.getClassLoader(),
                new Class[]{Collection.class},
                new InvocationHandler() {
                    ArrayList target = new ArrayList();
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args)
                            throws Throwable {
//                        ArrayList target = new ArrayList();
                        long beginTime = System.currentTimeMillis();
                        Object retVal = method.invoke(target, args);
                        long endTime = System.currentTimeMillis();
                        System.out.println(method.getName() + " running time ==  " + (endTime-beginTime));
                        return retVal;
                    }
        });
        proxy3.add("ddd");
        proxy3.add("aaa");
        proxy3.add("vvv");
        
        System.out.println(proxy1.toString());
        System.out.println(proxy2.toString());
        System.out.println(proxy3.toString());
        System.out.println(proxy3.size());
        System.out.println("end create instanse list ================================================ ");





规范的动态生成代理 相当于一个小框架aop

Advice.java

public interface Advice {
    void beforeMethod(Method method);
    void afterMethod(Method method);
}

MyAdvice.java

public class MyAdvice implements Advice {
    long beginTime = 0;
    public void afterMethod(Method method) {
        // TODO Auto-generated method stub
        System.out.println("毕业上班啦!");        
        long endTime = System.currentTimeMillis();
        System.out.println(method.getName() + " running time of " + (endTime - beginTime));

    }

    public void beforeMethod(Method method) {
        // TODO Auto-generated method stub
        System.out.println("来学习啦!");
        beginTime = System.currentTimeMillis();
    }
}


ProxyTest .java
public class ProxyTest {

    /**
     * @param args
     */
    public static void main(String[] args) throws Exception{
        // TODO Auto-generated method stub
        Class clazzProxy1 = Proxy.getProxyClass(Collection.class.getClassLoader(), Collection.class);
        System.out.println(clazzProxy1.getName());
        
        System.out.println("----------begin constructors list----------");
        /*$Proxy0()
        $Proxy0(InvocationHandler,int)*/
        Constructor[] constructors = clazzProxy1.getConstructors();
        for(Constructor constructor : constructors){
            String name = constructor.getName();
            StringBuilder sBuilder = new StringBuilder(name);
            sBuilder.append('(');
            Class[] clazzParams = constructor.getParameterTypes();
            for(Class clazzParam : clazzParams){
                sBuilder.append(clazzParam.getName()).append(',');
            }
            if(clazzParams!=null && clazzParams.length != 0)
                sBuilder.deleteCharAt(sBuilder.length()-1);
            sBuilder.append(')');
            System.out.println(sBuilder.toString());            
        }

        System.out.println("----------begin methods list----------");
        /*$Proxy0()
        $Proxy0(InvocationHandler,int)*/
        Method[] methods = clazzProxy1.getMethods();
        for(Method method : methods){
            String name = method.getName();
            StringBuilder sBuilder = new StringBuilder(name);
            sBuilder.append('(');
            Class[] clazzParams = method.getParameterTypes();
            for(Class clazzParam : clazzParams){
                sBuilder.append(clazzParam.getName()).append(',');
            }
            if(clazzParams!=null && clazzParams.length != 0)
                sBuilder.deleteCharAt(sBuilder.length()-1);
            sBuilder.append(')');
            System.out.println(sBuilder.toString());            
        }
        
        System.out.println("----------begin create instance object----------");
        //Object obj = clazzProxy1.newInstance();
        Constructor constructor = clazzProxy1.getConstructor(InvocationHandler.class);
        class MyInvocationHander1 implements InvocationHandler{

            public Object invoke(Object proxy, Method method, Object[] args)
                    throws Throwable {
                // TODO Auto-generated method stub
                return null;
            }
        
        }
        Collection proxy1 = (Collection)constructor.newInstance(new MyInvocationHander1());
        
        System.out.println(proxy1);
        proxy1.clear();
        //proxy1.size();
        //System.out.println("111111111111111");
        
        Collection proxy2 = (Collection)constructor.newInstance(new InvocationHandler(){

            public Object invoke(Object proxy, Method method, Object[] args)
                    throws Throwable {
                return null;
            }
            
        });
        
        final ArrayList target = new ArrayList();            
        Collection proxy3 = (Collection)getProxy(target,new MyAdvice());
        proxy3.add("zxx");
        proxy3.add("lhm");
        proxy3.add("bxd");
        System.out.println(proxy3.size());
        System.out.println(proxy3.getClass().getName());
    }

    private static Object getProxy(final Object target,final Advice advice) {
        Object proxy3 = Proxy.newProxyInstance(
                target.getClass().getClassLoader(),
                /*new Class[]{Collection.class},*/
                target.getClass().getInterfaces(),
                new InvocationHandler(){
                
                    public Object invoke(Object proxy, Method method, Object[] args)
                            throws Throwable {

                        /*long beginTime = System.currentTimeMillis();
                        Object retVal = method.invoke(target, args);
                        long endTime = System.currentTimeMillis();
                        System.out.println(method.getName() + " running time of " + (endTime - beginTime));
                        return retVal;*/
                        

                        advice.beforeMethod(method);
                        Object retVal = method.invoke(target, args);
                        advice.afterMethod(method);
                        return retVal;                        
                        
                    }
                }
                );
        return proxy3;
    }

}







  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

折腾数据折腾代码

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值