代理模式之动态代理
什么是动态代理
使用gdk动态代理模式
一个公共实现的接口
public interface UtilsProxy{
void print(String path, File file, String pstr, String codeformat);
}
一个实现类
public class Print implements UtilsProxy{
@Override
public void print(String path, File file, String pstr, String codeformat) {
System.out.println("invoke start");
System.out.println("invoke Print Print method");
System.out.println("invoke end");
}
}
实现一个代理类
public class UtilsProxyInvocationHandler implements InvocationHandler {
private UtilsProxy utilsProxy;
public UtilsProxyInvocationHandler(UtilsProxy utilsProxy) {
this.utilsProxy = utilsProxy;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if(args.length == 4){
File file = (File)args[1];
if (!file.exists()){
file.createNewFile();
}
utilsProxy.print((String)args[0],file,(String)args[2],(String)args[3]);
System.out.println("invoke UtilsProxyInvocationHandler invoke method start");
System.out.println("print:" + (String) args[2]);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(new FileOutputStream(file, true), (String)args[3]);
outputStreamWriter.write((String)args[2]);
outputStreamWriter.flush();
outputStreamWriter.close();
System.out.println("invoke UtilsProxyInvocationHandler invoke method end");
}
return null;
}
}
测试方法
public class Main {
public static void main(String[] args) {
UtilsProxy utilsProxy = new Print();
ClassLoader classLoader = utilsProxy.getClass().getClassLoader();
Class<?>[] interfaces = utilsProxy.getClass().getInterfaces();
UtilsProxyInvocationHandler utilsProxyInvocationHandler = new UtilsProxyInvocationHandler(utilsProxy);
UtilsProxy o = (UtilsProxy)Proxy.newProxyInstance(classLoader, interfaces, utilsProxyInvocationHandler);
File file = new File("");
o.print("",file,"helloword!","utf-8");
}
}
实现gdk动态代理模式