package net.ynyee.proxy2; public interface ICat { public void eat(); public void sleep(); } package net.ynyee.proxy2; public class Cat implements ICat { @Override public int eat() { System.out.println("吃东西.."); return 0; } @Override public void sleep() { System.out.println("睡觉.."); } } package net.ynyee.proxy2; public class CatIntercepter { public void one(){ System.out.println("one"); } public void two(){ System.out.println("two"); } } package net.ynyee.proxy2; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; public class ProxyHandler implements InvocationHandler { public void setTarget(Object target) { this.target = target; } private Object target = null; CatIntercepter catIntercepter = new CatIntercepter(); @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { Object result = null; if (method.getName().equals("eat")) { catIntercepter.one(); result = method.invoke(target, args); catIntercepter.two(); } else { result = method.invoke(target, args); } return result; } } package net.ynyee.proxy2; import java.lang.reflect.Proxy; public class ProxyFactory { public static Object getProxy(Object target) { ProxyHandler handler = new ProxyHandler(); handler.setTarget(target); return Proxy.newProxyInstance(ICat.class.getClassLoader(), target .getClass().getInterfaces(), handler); } } package net.ynyee.proxy2; public class Test { public static void main(String[] args) { ICat cat = new Cat(); ICat proxy = null; Object obj = ProxyFactory.getProxy(cat); if (obj instanceof ICat) { proxy = (ICat) obj; } proxy.eat(); } }