cglib

import net.sf.cglib.core.NamingPolicy;
import net.sf.cglib.proxy.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Method;
import java.util.jar.Attributes;

/**
 * Created by geyingchao on 2017/6/9.
 */
public class Aproxy implements MethodInterceptor ,CallbackFilter {

    private static final Logger LOGGER= LoggerFactory.getLogger(Aproxy.class);
    public Object intercept(Object obj, Method method, Object[] arg, MethodProxy proxy) throws Throwable {
        LOGGER.error("Before:"+method);
        System.out.println("Before:"+method);
        Object object=proxy.invokeSuper(obj, arg);
        LOGGER.error("After:"+method);
        System.out.println("After:"+method);
        return object;
    }

    @Override
    public int accept(Method method) {
            if("methodA".equals(method.getName())){
                return 0;
            }else if("methodB".equals(method.getName())){
                return 1;
            }else if("methodC".equals(method.getName())){
                return 2;
            }
            return 0;
    }

    public static Object createProxy(Object target){
        Enhancer enhancer=new Enhancer();
        Callback noOp= NoOp.INSTANCE;
        Callback[] callbacks={new Aproxy(),noOp,new Aproxy().new InnerDefaultValue()};
        enhancer.setSuperclass(target.getClass());
        enhancer.setCallbacks(callbacks);
        enhancer.setCallbackFilter(new Aproxy());
        return enhancer.create();
    }

    class InnerDefaultValue implements Dispatcher{

        @Override
        public Object loadObject() throws Exception {
            System.out.println("lazy init...");
           return new Aproxy();
        }
    }

    public String methodA(){
        System.out.println("methodA");
        return "methodA";
    }

    public String methodB(){
        System.out.println("methodB");
        return "methodB";
    }
    public String methodC(){
        System.out.println("methodC");
        return "methodC";
    }

    public static Class createInterface(Object obj){
        InterfaceMaker im=new InterfaceMaker();
        im.add(obj.getClass());
        Class interfaceOjb=im.create();
        System.out.println(interfaceOjb.isInterface());//true
        System.out.println(interfaceOjb.getName());//n
        return interfaceOjb;
    }

    public static void main(String[] args) {
        Aproxy result=(Aproxy)Aproxy.createProxy(new Aproxy());
        result.methodC();
        Aproxy.createInterface(new Aproxy());
    }

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值