类图
源码
(1) Customer.java package proxytest; public class Customer implements Person{ public void findLove(){ System.out.println("高富帅"); System.out.println("身高180cm"); System.out.println("有6块腹肌"); System.out.println("未满18岁"); } } (2) JDKMeipo.java package proxytest; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; public class JDKMeipo implements InvocationHandler{ // 被代理的对象,把引用保存下来 private Object target; public Object getInstance(Object target) throws Exception{ this.target = target; Class<?> clazz = target.getClass(); return Proxy.newProxyInstance(clazz.getClassLoader(),clazz.getInterfaces(),this); } public Object invoke( Object proxy, Method method, Object[] args ) throws Throwable{ before(); Object obj = method.invoke(this.target,args); after(); return obj; } private void before(){ System.out.println("我是媒婆:我给你找对象,现在已经确认你的需求"); System.out.println("开始物色"); } private void after(){ System.out.println("未满18岁,对不起不能早恋!!"); } } (3) Person.java package proxytest; public interface Person { public void findLove(); } (4) Test.java package proxytest; public class Test { public static void main(String[] args){ try { Person obj = (Person)new JDKMeipo().getInstance(new Customer()); obj.findLove(); } catch (Exception e) { e.printStackTrace(); } } }
测试截图