1 16 package scriptella.util; 17 18 import java.lang.reflect.InvocationHandler ; 19 import java.lang.reflect.InvocationTargetException ; 20 import java.lang.reflect.Method ; 21 import java.lang.reflect.Proxy ; 22 23 33 public class ProxyAdapter<T> { 34 private final T proxy; 35 36 @SuppressWarnings ("unchecked") 37 public ProxyAdapter(Class ... interfaces) { 38 proxy = (T) Proxy.newProxyInstance(getClass().getClassLoader(), interfaces, new InvocationHandler () { 39 public Object invoke(Object proxy, Method method, Object [] args) throws Throwable { 40 Method m; 41 try { 42 m = ProxyAdapter.this.getClass().getMethod(method.getName(), method.getParameterTypes()); 44 m.setAccessible(true); 45 } catch (Exception e) { throw new UnsupportedOperationException (method.toString(), e); 47 48 } 49 try { 51 return m.invoke(ProxyAdapter.this, args); 52 } catch (InvocationTargetException e) { 53 throw e.getCause(); 54 } 55 } 56 }); 57 } 58 59 62 public T getProxy() { 63 return proxy; 64 } 65 66 67 70 public static void main(String [] args) throws Exception { 71 ProxyAdapter<Appendable > pa = new ProxyAdapter(Appendable .class) { 73 private StringBuilder sb = new StringBuilder (); 74 public Appendable append(char c) { 76 System.out.println("Proxy append(char c) method. Append "+c); 77 sb.append(c); 78 return (Appendable ) getProxy(); 79 } 80 81 public String toString() { 82 return "Proxy toString method: "+sb; 83 } 84 85 }; 86 final Appendable a = pa.getProxy(); 87 a.append('1').append('2'); 88 System.out.println("a.toString() = " + a.toString()); 89 a.append("Not implemented"); 91 92 } 93 } 94 | Popular Tags |