public class Station { public void sellTicket(){ System.out.println("已经卖出"); } }
public class ProxyFactory implements MethodInterceptor { private Station station = new Station(); public Station getStation(){ //创建enhancer对象,类似于Proxy Enhancer enhancer = new Enhancer(); //传入要被动态代理的类 enhancer.setSuperclass(Station.class); //设置回调函数,传入对象要实现 MethodInterceptor enhancer.setCallback(this); //创建匿名内部类继承setSuperClass()传入的类 Station station1 =(Station) enhancer.create(); return station1; } @Override public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable { System.out.println("已经收取手续费"); Object result = method.invoke(station, objects); System.out.println("打印结果"); return result; } }
public class Client { public static void main(String[] args) { //创建代理工厂 ProxyFactory proxyFactory = new ProxyFactory(); //获取继承Station的匿名内部类 Station station = proxyFactory.getStation(); //调用sellTicket() station.sellTicket(); //获得匿名匿名内部类的class文件名 System.out.println(station.getClass()); while (true){ } } }
public class Station$$EnhancerByCGLIB$$6977634a
extends Station
implements Factory {
private boolean CGLIB$BOUND;
private static final ThreadLocal CGLIB$THREAD_CALLBACKS;
private static final Callback[] CGLIB$STATIC_CALLBACKS;
private MethodInterceptor CGLIB$CALLBACK_0;
private static final Method CGLIB$sellTicket$0$Method;
private static final MethodProxy CGLIB$sellTicket$0$Proxy;
private static final Object[] CGLIB$emptyArgs;
private static final Method CGLIB$finalize$1$Method;
private static final MethodProxy CGLIB$finalize$1$Proxy;
private static final Method CGLIB$equals$2$Method;
private static final MethodProxy CGLIB$equals$2$Proxy;
private static final Method CGLIB$toString$3$Method;
private static final MethodProxy CGLIB$toString$3$Proxy;
private static final Method CGLIB$hashCode$4$Method;
private static final MethodProxy CGLIB$hashCode$4$Proxy;
private static final Method CGLIB$clone$5$Method;
private static final MethodProxy CGLIB$clone$5$Proxy;
public Station$$EnhancerByCGLIB$$6977634a() {
Station$$EnhancerByCGLIB$$6977634a station$$EnhancerByCGLIB$$6977634a = this;
Station$$EnhancerByCGLIB$$6977634a.CGLIB$BIND_CALLBACKS(station$$EnhancerByCGLIB$$6977634a);
}
static {
Station$$EnhancerByCGLIB$$6977634a.CGLIB$STATICHOOK1();
}
protected final void finalize() throws Throwable {
MethodInterceptor methodInterceptor = this.CGLIB$CALLBACK_0;
if (methodInterceptor == null) {
Station$$EnhancerByCGLIB$$6977634a.CGLIB$BIND_CALLBACKS(this);
methodInterceptor = this.CGLIB$CALLBACK_0;
}
if (methodInterceptor != null) {
Object object = methodInterceptor.intercept(this, CGLIB$finalize$1$Method, CGLIB$emptyArgs, CGLIB$finalize$1$Proxy);
return;
}
super.finalize();
}