動態(tài)代理比起靜態(tài)代理方便的多,但是jdk動態(tài)代理實現(xiàn)必須通過接口,如果要代理一個沒有接口的類jdk動態(tài)就無法實現(xiàn)了,這個時候就要借助CGlib這個類庫來動態(tài)生成代理類(spring hibernate框架都使用了該類庫,使用前要先導(dǎo)入)
package proxy;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
import java.lang.reflect.Method;
public class CGlibProxy implements MethodInterceptor {
public <T> T getProxy(Class<T> tClass) {
return (T) Enhancer.create(tClass, this);
}
@Override
public Object intercept(Object object, Method method, Object[] args, MethodProxy proxy) throws Throwable {
before();
Object result = proxy.invokeSuper(object, args);
after();
return result;
}
public void before() {
System.out.println("before");
}
public void after() {
System.out.println("after");
}
public static void main(String[] args) {
CGlibProxy cGlibProxy = new CGlibProxy();
Hello helloProxy = cGlibProxy.getProxy(Hello.class);
helloProxy.sayHello("world");
}
}
關(guān)于Hello類:
package proxy;
public class Hello {
public void sayHello(String name) {
System.out.println("hello " + name);
}
}