@Test public void testJDKProxy() { Human p = new Person("vvf"); PersonHandler h = new PersonHandler(p); Human o = (Human) Proxy.newProxyInstance( p.getClass().getClassLoader(), p.getClass().getInterfaces(), h); o.showName(); }
interface Human { void showName(); }
class Person implements Human { String name;
public Person(String name) { this.name = name; }
public Person() { }
public void showName() { System.out.println(this.name); } }
class PersonHandler implements InvocationHandler {
Object target;
public PersonHandler(Object target) { this.target = target; }
Object r = method.invoke(target, args); if (method.getName().equals("run")) { System.out.println("run after"); } else { System.out.println("speak after"); } return r; } }
public static void main(String[] args) { Person p = new Person(); HumanProxyHandler humanProxyHandler = new HumanProxyHandler(p); Object o = Proxy.newProxyInstance( p.getClass().getClassLoader() , p.getClass().getInterfaces() , humanProxyHandler); Human h = (Human) o; h.run(); h.speak(); VIP v = (VIP) o; v.vipService(); }
@Test public void testCGLIProxy() { Person person = PersonProxyFactory.createProxy(); person.showName(); } class PersonProxyFactory { public static Person createProxy() { Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(Person.class); enhancer.setCallback(new PersonProxy()); Object r = enhancer.create(); return (Person) r; }
public static Person createProxy(Class[] cls, Object[] args) { Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(Person.class); enhancer.setCallback(new PersonProxy()); Object r = enhancer.create(cls, args); return (Person) r; } }
class PersonProxy implements MethodInterceptor {
@Override public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable { System.out.println("before"); Object r = methodProxy.invokeSuper(o, objects); System.out.println("after"); return r; } }
class Person { String name;
public Person(String name) { this.name = name; }
public Person() { }
public void showName() { System.out.println(this.name); } }