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");
}
}