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

jdk动态代理

时间:2018-07-31 23:36:32      阅读:195      评论:0      收藏:0      [点我收藏+]

标签:get   erp   lan   interface   tproxy   tcl   extc   voc   eth   

package proxy.jdk;

public interface UserDao {

    public void add();
    public void delete();
    
}
package proxy.jdk;

public class UserDaoimpl implements UserDao{

    @Override
    public void add() {
        // TODO Auto-generated method stub
        System.out.println("user add success!");
    }

    @Override
    public void delete() {
        // TODO Auto-generated method stub
        System.out.println("user delete success!");
    }

}
package proxy.jdk;

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

public class Handler implements InvocationHandler{

    public Object target;
    
    public Handler(Object target) {
        super();
        this.target = target;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args)
            throws Throwable {
        // TODO Auto-generated method stub
        System.out.println("代理执行前");
        Object o = method.invoke(target, args);
        System.out.println("代理执行后");
        return o;
    }
    
    public Object getProxy() {
        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), target.getClass().getInterfaces(), this);
    }

}
package proxy.jdk;

public class Test {

    public static void main(String[] args) {
        
        UserDao userDao=new UserDaoimpl();
        Handler handler=new Handler(userDao);
        UserDao userProxy = (UserDao) handler.getProxy();
        userProxy.add();
        userProxy.delete();
        
    }
}

 

jdk动态代理

标签:get   erp   lan   interface   tproxy   tcl   extc   voc   eth   

原文地址:https://www.cnblogs.com/Danial7777777/p/9398612.html

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