码迷,mamicode.com
首页 > 其他好文 > 详细

jdk动态代理实现

时间:2016-12-04 14:03:50      阅读:173      评论:0      收藏:0      [点我收藏+]

标签:动态代理   blog   proxy   super   void   接口   pre   owa   targe   

1、jdk动态代理的简单实现类

package com.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class JDKProxy implements InvocationHandler{

    private Object target;//目标对象
    
    public JDKProxy(Object target) {
        super();
        this.target = target;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("--------------------invoke-before----------------------");
        Object object = method.invoke(target, args);
        System.out.println("--------------------invoke-after----------------------");
        return object;
    }
    
    public Object getProxy(){
        return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), this);
    }
    

}

2、测试用接口和接口实现

package com.proxy.manager;

public interface HelloWorldManager {
    
    public void sayHello();

}
package com.proxy.manager.impl;

import com.proxy.manager.HelloWorldManager;

public class HelloWorldManagerImpl implements HelloWorldManager {

    @Override
    public void sayHello() {
        System.out.println("Hello World!");
    }

}

3、测试类

package com.proxy.test;

import com.proxy.JDKProxy;
import com.proxy.manager.HelloWorldManager;
import com.proxy.manager.impl.HelloWorldManagerImpl;

public class JDKProxyTest {
    
    public static void main(String[] args) {
        HelloWorldManager hw = new HelloWorldManagerImpl();
        JDKProxy jdkProxy = new JDKProxy(hw);
        HelloWorldManager hellWorldManager = (HelloWorldManager) jdkProxy.getProxy();
        hellWorldManager.sayHello();
    }

}

4、测试输出接口

--------------------invoke-before----------------------
Hello World!
--------------------invoke-after----------------------

 

jdk动态代理实现

标签:动态代理   blog   proxy   super   void   接口   pre   owa   targe   

原文地址:http://www.cnblogs.com/miaoyf/p/6130592.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!