JDK与cglib动态代理

JDK:

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

public class JDKProxyTest {

    public static Object createProxy(Object object){
        //jdk的动态代理方法
        //可用于日志管理,动态代理等
        ClassLoader classLoader = object.getClass().getClassLoader();
        Class<?>[] interfaces = object.getClass().getInterfaces();
        return Proxy.newProxyInstance(classLoader, interfaces, (Object proxy, Method method, Object[] args) ->{

            Class<?>[] interfaces1 = proxy.getClass().getInterfaces();
            Field[] fields = interfaces[0].getFields();

            String methodName = method.getName();
            System.out.println("正在执行"+methodName+"方法");
            return method.invoke(object, args);
        });
    }

    static interface User{
        public void setName(String name);
        public String getName();
    }

    static class UserImpl implements User {

        String name;
        String phone;
        int age;

        public UserImpl(String userName){
            this.name = userName;
        }

        @Override
        public void setName(String name) {
            this.name = name;
        }

        @Override
        public String getName() {
            return name;
        }
    }

    public static void main(String[] args) {
        User user = (User)createProxy(new UserImpl("张三"));

        user.setName("李四");

        String name = user.getName();

        System.out.println(name);
    }

}

cglib:

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

public class CglibProxyTest {

    public static Object createProxy(Object object){
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(object.getClass());
        enhancer.setCallback(new MethodInterceptor() {
            @Override
            public Object intercept(Object o, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
                System.out.println("正在执行"+method.getName()+"方法");
                return method.invoke(object, args);
            }
        });
        return enhancer.create();
    }

    public static void main(String[] args) {
        Usern user = new Usern("wanger");
        Usern userimpl = (Usern) createProxy(user);
        String name = userimpl.getName();
        System.out.println(name);

    }

    static class Usern{
        String name;
        int age;

        public Usern(){

        }

        public Usern(String name){
            this.name = name;
        }

        public String getName(){
            return name;
        }
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值