1.JDK动态代理,只能代理接口
2.CGLIB动态代理,不能代理final方法
package service;
public class HelloService {
public String sayHello(String str)
{
return ("Hello "+str);
}
final public String sayGoodbye(String str)
{
return "goodbye "+str;
}
}
package service;
import java.lang.reflect.Method;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
class MyInterceptor implements MethodInterceptor
{
HelloService hs;
public HelloService getHs() {
return hs;
}
public void setHs(HelloService hs) {
this.hs = hs;
}
@Override
public Object intercept(Object object, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
System.out.println("before......");
return methodProxy.invokeSuper(object, args);
}
}
public class ProxyService {
public static HelloService getProxy()
{
Enhancer enhancer=new Enhancer();
enhancer.setSuperclass(HelloService.class);
enhancer.setCallback(new MyInterceptor());
return (HelloService)enhancer.create();
}
}
package action;
import service.HelloService;
import service.ProxyService;
public class TestProxy {
public static void main(String[] args) {
HelloService hs=ProxyService.getProxy();
// System.out.println(hs.sayHello("tianda"));
System.out.println(hs.sayGoodbye("tianda"));
}
}