JAVA 反射 (jdk + cglib)

jdk

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

import static java.lang.System.out;

// 定义接口
interface IHello {
    public void hello(String name);
}

// 实现接口
class HelloImpl implements IHello {
    @Override
    public void hello(String name) {
        out.println("Hello, " + name);
    }
}

// 代理实现
class HelloProxyImpl implements InvocationHandler {
    private Object delegate;

    public Object bind(Object delegate) {
        this.delegate = delegate;
        return Proxy.newProxyInstance(delegate.getClass().getClassLoader(),
                delegate.getClass().getInterfaces(), this);
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args)
            throws Throwable {
        Object result = null;
        try {
             result = method.invoke(delegate, args);
         } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}

// 测试
public class Main {
    public static void main(String[] args) {
        IHello helloProxy = (IHello) new HelloProxyImpl().bind(new HelloImpl());
        helloProxy.hello("Spring");
    }
}

cglib

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

import static java.lang.System.out;

class Hello {
    public void greeting(String who) {
        out.println("hello," + who);
    }
}

class CGLIBLoggerProxy implements MethodInterceptor {

    public Object bind(Object delegate) {
        Enhancer enhancer = new Enhancer();
        enhancer.setCallback(this);
        enhancer.setSuperclass(delegate.getClass());
        return enhancer.create();
    }

    public Object intercept(Object o, Method method, Object[] args, MethodProxy proxy)
            throws Throwable {
        out.println("starting...");
        Object result = proxy.invokeSuper(o, args);
        out.println("stopping...");
        return result;
    }
}

public class CGLIB {
    public static void main(String[] args) {
        Hello hello = (Hello) new CGLIBLoggerProxy().bind(new Hello());
        hello.greeting("leno");
    }
}

 

 

转载于:https://my.oschina.net/caiyuan/blog/7702

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值