//送礼物 被代理对象的接口 public interface SendGift { void sendHower(); }
//追求者 public class Persuit implements SendGift{ private Girl girl;
public Persuit(Girl girl){ this.girl = girl; }
@Override public void sendHower() { System.out.println(girl.getName() + "给你花");
} }
//学生1 public class Student1 implements SendGift{
private SendGift sendGift;
public Student1(SendGift sendGift){ this.sendGift = sendGift; }
@Override public void sendHower() { System.out.println("我是同学1,我是帮忙的");
sendGift.sendHower();
System.out.println("我是同学1,我帮忙结束"); } }
public class Student2 implements SendGift { private SendGift sendGift;
public Student2(SendGift sendGift){ this.sendGift = sendGift; }
@Override public void sendHower() { System.out.println("我是同学2,我是帮忙的");
sendGift.sendHower();
System.out.println("我是同学2,我帮忙结束"); } }
//测试类 public class Client { public static void main(String[] args) { Girl girl = new Girl("zs"); Persuit persuit = new Persuit(girl); //先学生1,后学生2 Student2 student2 = new Student2(persuit); Student1 student1 = new Student1(student2); student1.sendHower();
//先学生2,后学生1 Student1 student1 = new Student1(persuit); Student2 student2 = new Student2(student1); student2.sendHower(); } }
Object ret = null; try { //调用目标方法 ret = method.invoke(target, args); } catch (Exception e) { System.out.println("调用发生异常"); throw e; }
System.out.println("被代理对象方法执行后");
return ret; } }
1 2 3 4 5 6 7 8 9 10 11 12 13
//客户端测试类 public class Client { public static void main(String[] args) { ProxyHandler handler = new ProxyHandler(); Subject subject = (Subject) handler.newProxyInstance(new ConcreteSubject()); subject.request();
ProxyHandler handler2 = new ProxyHandler(); //不能代理无接口的类Fish,Proxy中target.getClass().getInterfaces()报错 Fish fish = (Fish) handler.newProxyInstance(new ConcreteSubject()); fish.getWater(); } }
测试的控制台显示:
1 2 3 4 5
被代理对象方法执行前 执行request方法 被代理对象方法执行后 Exception in thread "main" java.lang.ClassCastException: com.sun.proxy.$Proxy0 cannot be cast to proxy.Fish at proxy.Client.main(Client.java:10)