代码语言:javascript复制
interface AService{
void fly();
}
class AServiceImpl implements AService{
@Override
public void fly(){
System.out.println("fly......");
}
}
代码语言:javascript复制// jdk自带动态代理实现方式
class JDKHandler implements InvocationHandler {
private Object obj;
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// proxy是生成的代理类对象
System.out.println("开始时间:" System.currentTimeMillis());
Object ret = method.invoke(obj,args);
System.out.println("结束时间:" System.currentTimeMillis());
return ret; // 返回原方法的结果
}
public JDKHandler(Object obj){
this.obj = obj;
}
}
代码语言:javascript复制// cglib方式
class CglibHandler implements MethodInterceptor {
@Override
public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
// proxy 是代理的方法对象
System.out.println("开始时间:" System.currentTimeMillis());
Object ret = proxy.invokeSuper(obj,args); // 注意此处是invokSuper
System.out.println("结束时间:" System.currentTimeMillis());
return ret
}
}
代码语言:javascript复制public class Main {
public static void main(String[] args) {
AService service = new AServiceImpl();
AService proxy = (AService) Proxy.newProxyInstance(
AService.class.getClassLoader(),
service.getClass().getInterfaces(),
// 此处是子类实现的接口,根据子类获取,不能根据接口类获取
// Aservice.class.getInterfaces() 错误
// AserviceImpl.class.getInterfaces()
new JDKHandler(service));
proxy.fly();
}
}
代码语言:javascript复制public class Main {
public static void main(String[] args) {
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(AServiceImpl.class);// 此处是子类,不是接口,要注意
enhancer.setCallback(new CglibHandler());
((AServiceImpl) enhancer.create()).fly();
}
}