JAVA学習--反射の動的エージェントモード

7085 ワード

 1 import java.lang.reflect.InvocationHandler;

 2 import java.lang.reflect.Method;

 3 import java.lang.reflect.Proxy;

 4 

 5 //

 6 interface Subject {

 7     void action();

 8 }

 9 

10 //     

11 class RealSubject implements Subject {

12     public void action() {

13         System.out.println("      ,       !  ~~");

14     }

15 }

16 

17 class MyInvocationHandler implements InvocationHandler {

18     Object obj;//                 

19 

20     // ①          ②          

21     public Object blind(Object obj) {

22         this.obj = obj;

23         return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj

24                 .getClass().getInterfaces(), this);

25     }

26     //                      ,         invoke     

27     @Override

28     public Object invoke(Object proxy, Method method, Object[] args)

29             throws Throwable {

30         //method       returnVal

31         Object returnVal = method.invoke(obj, args);

32         return returnVal;

33     }

34 

35 }

36 

37 public class TestProxy {

38     public static void main(String[] args) {

39         

40         //1.       

41         RealSubject real = new RealSubject();

42         //2.       InvacationHandler       

43         MyInvocationHandler handler = new MyInvocationHandler();

44         //3.  blind()  ,            real        Subject       。

45         Object obj = handler.blind(real);

46         Subject sub = (Subject)obj;//  sub        

47         

48         sub.action();//   InvacationHandler       invoke()     

49         

50         //    

51         NikeClothFactory nike = new NikeClothFactory();

52         ClothFactory proxyCloth = (ClothFactory)handler.blind(nike);//proxyCloth        

53         proxyCloth.productCloth();

54         

55         

56         

57     }

58 }