动态代理理解
从这张图上看,动态代理也可以用在真正类外面包裹一层普通处理类来实现, 这样做的坏处是
不能扩展,每一个真正类都需要自己的一个代理类,而动态代理可以用一个Proxy类对所有的有接口实现的真正类进行代理。
public class DPMain { public static PDQueryStatus create(DPQueryStatusImpl dpqs) { //定义转发处理类 DPInvocationHandler handler = new DPInvocationHandler(dpqs); //定义了一个 Class<?>[] interfaces=new Class[] { PDQueryStatus.class }; Object result = Proxy.newProxyInstance(dpqs.getClass().getClassLoader(), interfaces, handler);
//核心在这里,handler可以对interfaces接口数组中的方法进行转发处理 //Class<?> proxy=Proxy.getProxyClass(dpqs.getClass().getClassLoader(), // interfaces); //System.out.println("Proxy class name: "+proxy.getCanonicalName()); // System.out.println("Proxy's super class name: "+proxy.getSuperclass().getName()); // System.out.println(); return (PDQueryStatus) result; } /** * @param args */ public static void main(String[] args) { try { PDQueryStatus query = DPMain.create(new DPQueryStatusImpl()); DPFileStatus status = query.getFileStatus("/tmp/testDP"); System.out.println(status); } catch (Exception e) { e.printStackTrace(); } } }
public class DPFileStatus { private String filename; private long time; public DPFileStatus(String filename) { this.filename=filename; this.time=(new Date()).getTime(); } public String getFilename() { return filename; } public void setFilename(String filename) { this.filename = filename; } public long getTime() { return time; } public void setTime(long time) { this.time = time; } public String toString() { return "File: "+filename+" Create at "+(new Date(time)); } }
public interface PDQueryStatus { DPFileStatus getFileStatus(String filename); }
public class DPInvocationHandler implements InvocationHandler { private DPQueryStatusImpl dpqs; public DPInvocationHandler(DPQueryStatusImpl dpqs) { this.dpqs = dpqs; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { Object ret = null; String msg1 = MessageFormat.format("Calling method {0}({1})", method.getName(), Arrays.toString(args)); System.out.println(msg1); ret = method.invoke(dpqs, args); String msg2 = MessageFormat.format("Method {0} returned with ({1})", method.getName(), ret.toString()); System.out.println(msg2); return ret; } }
public class DPQueryStatusImpl implements PDQueryStatus { @Override public DPFileStatus getFileStatus(String filename) { DPFileStatus status=new DPFileStatus(filename); System.out.println("Method getFileStatus Called, return: "+status); return status; } }