[Java] 动态代理实现AOP →→→→→进入此内容的聊天室

来自 , 2019-08-26, 写在 Java, 查看 97 次.
URL http://www.code666.cn/view/4fa7c625
  1. interface human{
  2.         void info();
  3.         void fly();
  4.        
  5. }
  6.  
  7. class SuperMan implements human{
  8.         public void info(){
  9.                 System.out.println("我是超人");
  10.         }
  11.         public void fly(){
  12.                 System.out.println("I can fly");
  13.         }
  14. }
  15. class HumanUtil{
  16.         public void method1(){
  17.                 System.out.println("=========方法一=============");
  18.         }
  19.        
  20.         public void method2(){
  21.                 System.out.println("=========方法二=============");
  22.         }
  23. }
  24.  class MyInvocationHandler implements InvocationHandler{
  25.         //被代理对象声明
  26.          Object obj;
  27.          
  28.          public void setObject(Object obj){
  29.                  this.obj=obj;
  30.          }
  31.  
  32.         @Override
  33.         public Object invoke(Object proxy, Method method, Object[] args)
  34.                         throws Throwable {
  35.                 HumanUtil h = new HumanUtil();
  36.                 h.method1();
  37.                 Object returlVal=method.invoke(obj, args);
  38.                 h.method2();
  39.                 return returlVal;
  40.         }
  41.          
  42.  }
  43.  
  44.  class MyProxy{
  45.          //动态的创建一个代理类对象
  46.          public static Object getProxyInstance(Object obj){
  47.                  MyInvocationHandler handler = new MyInvocationHandler();
  48.                  handler.setObject(obj);
  49.                  return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(), handler);
  50.          }
  51.  }
  52. public class testAop {
  53.        
  54.         public static  void main(String[] args){
  55.                 SuperMan man= new SuperMan();
  56.                 Object obj=MyProxy.getProxyInstance(man);
  57.                
  58.                 human hu=(human)obj;
  59.                 hu.info();
  60.                 System.out.println();
  61.                 hu.fly();
  62.                
  63.         }
  64.  
  65. }
  66.  

回复 "动态代理实现AOP"

这儿你可以回复上面这条便签

captcha