标签:
/** * Created by sten on 7/12/16. */ public interface Person { void eat() ; } /** * Created by sten on 7/12/16. */ public class Chinese implements Person { @Override public void eat() { System.out.print("eat fish."); } } /** * Created by sten on 7/12/16. */ public class InvocationTest implements InvocationHandler { private Person person ; public InvocationTest(Person person) { this.person = person ; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { return method.invoke(person, args); } } /** * Created by sten on 7/12/16. */ public class Main { public static void main(String[] args) { Chinese chinese = new Chinese() ; Person person = (Person) Proxy.newProxyInstance(Person.class.getClassLoader(), new Class[]{Person.class}, new InvocationTest(chinese)); person.eat(); } }
/** * Created by sten on 7/12/16. */ public class SqlMap { private Map<String, String> map = new HashedMap() ; public SqlMap() { map.put("Class1.method1","select sql1") ; map.put("Class1.method2","delete sql1") ; map.put("Class1.method3","update sql1") ; map.put("Class1.method4","insert sql1") ; map.put("Class2.method1","select sql2") ; map.put("Class2.method2","delete sql2") ; map.put("Class2.method3","update sql2") ; map.put("Class2.method4","insert sql2") ; } public String getSql(String classNameMethodName) { return map.get(classNameMethodName) ; } }
/** * Created by sten on 7/12/16. */ public interface Class1 { String method1() ; String method2() ; String method3() ; String method4() ; }
/** * Created by sten on 7/12/16. */ public class InvocationSql implements InvocationHandler { private Class interfaceObject ; private SqlMap sqlMap ; public InvocationSql(Class interfaceObject, SqlMap sqlMap) { this.interfaceObject = interfaceObject ; this.sqlMap = sqlMap ; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { String key = interfaceObject.getClass().getName() + "." + method.getName() ; String value = sqlMap.getSql(key) ; return value ; } }
/** * Created by sten on 7/12/16. */ public class TargetProxy<T> { public T getTarget(Class<T> interfaceObject, SqlMap sqlMap) { InvocationSql invocationSql = new InvocationSql(interfaceObject, sqlMap) ; return (T)newProxyInstance(interfaceObject.getClassLoader(),new Class[] {interfaceObject}, invocationSql) ; } }
/** * Created by sten on 7/12/16. */ public class Bitis { public static void main(String[] args) { TargetProxy targetProxy = new TargetProxy() ; Class1 class1 = (Class1) targetProxy.getTarget(Class1.class, new SqlMap()); class1.method1() ; } }
标签:
原文地址:http://www.cnblogs.com/sten/p/5664911.html