package com.proxy.staticproxy;public interface SellTicket {void sell();
}
package com.proxy.staticproxy;public class TrainStation implements SellTicket{@Overridepublic void sell() {System.out.println("火车站售票");}}
package com.proxy.staticproxy;public class ProxyPoint implements SellTicket{//声明火车类对象private TrainStation trainStation = new TrainStation();@Overridepublic void sell() {System.out.println("代售点收取服务费");trainStation.sell();}public static void main(String[] args) {ProxyPoint proxyPoint = new ProxyPoint();proxyPoint.sell();}
}
package com.proxy.jdkproxy;import com.proxy.staticproxy.SellTicket;
import com.proxy.staticproxy.TrainStation;import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;public class ProxyFactory {private TrainStation trainStation = new TrainStation();public SellTicket getProxyPoint() {/*** ClassLoader loader: 类加载器,用于加载代理类。可以通过目标对象获取类加载器* Class>[] interfaces: 代理类实现的接口的字节码对象* InvocationHandler h: 代理对象的调用处理程序*/SellTicket sellTicket = (SellTicket)Proxy.newProxyInstance(trainStation.getClass().getClassLoader(), trainStation.getClass().getInterfaces(),new InvocationHandler() {/*** @param proxy 代理对象 proxyObject是同一个对象,在invoke方法中基本不用* @param method 对接口中的方法进行封装的method对象* @param args 调用方法的实际参数* @return 方法返回值* @throws Throwable*/@Overridepublic Object invoke(Object proxy, Method method, Object[] args) throws Throwable {// 代码增强System.out.println("代理点收取服务费");Object object = method.invoke(trainStation, args);return object;}});return sellTicket;}public static void main(String[] args) {ProxyFactory proxyPoint = new ProxyFactory();SellTicket sellTicket = proxyPoint.getProxyPoint();sellTicket.sell();}
}
cglib cglib 2.2.2
package com.cglib;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 ProxyFactory implements MethodInterceptor {private TrainStation trainStation = new TrainStation();public TrainStation getTrainStation(){//创建Enhancer对象,类似于JDK代理中的Proxy类Enhancer enhancer = new Enhancer();//设置父类的字节码对象enhancer.setSuperclass(TrainStation.class);//设置回调函数enhancer.setCallback(this);//创建代理对象TrainStation trainStation = (TrainStation)enhancer.create();return trainStation;}public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {// 代码增强System.out.println("代售点收取服务费用");Object obj = method.invoke(trainStation, objects);return obj;}public static void main(String[] args) throws Exception {ProxyFactory proxyFactory = new ProxyFactory();TrainStation trainStation = proxyFactory.getTrainStation();trainStation.sell();}
}
上一篇:第二章.应用层