代理模式的运用,AOP日志记录

动态代理可以实现AOP,比如日志记录。可以记录下每个方法的执行时间 ,名称和花费时间。代码如下:

import java.lang.reflect.InvocationHandler;  
import java.lang.reflect.InvocationTargetException;  
import java.lang.reflect.Method;  
import java.lang.reflect.Proxy;  
import java.util.Date;
  
interface   DoAction{  
    public void ViewAction();  
    public void AddAction();  
}  
  
class DoActionImpl implements DoAction {  
      
    public void ViewAction(){  
        System.out.println("查看信息!");  
    }  
      
    public void AddAction(){  
        System.out.println("添加信息!");  
    }  
}  
  
  
class ProxyAction implements InvocationHandler {  
    private Object action;  
    private User user = new User() ;  
      
    public ProxyAction(Object action) {  
        this.action = action;  
    }  
  
    public static Object getInstance(Object action) {  
        return Proxy.newProxyInstance(action.getClass().getClassLoader(),  
                action.getClass().getInterfaces(), new ProxyAction(action));  
    }  
  
    public Object invoke(Object proxy, Method m, Object[] args)  
            throws Throwable {  
    	Date start = null;
    	Date end;
        Object result = null;  
        try {  
            // 在委派之前作动作,如权限判断等  
        	start = new Date();
            // 进行委派  
            result = m.invoke(action, args);  
  
        } catch (InvocationTargetException e) {  
  
            throw e.getTargetException();  
  
        } catch (Exception e) {  
  
            throw new RuntimeException("unexpected invocation exception: "  
  
            + e.getMessage());  
  
        } finally {  
            // 在委派之后做动作  
        	end = new Date();
        	System.out.println(start+":"+m.getName()+"方法被执行,花费时间"+(end.getTime() -start.getTime()) );
        }  
  
        return result;  
  
    }  
  
}  
  
//用户信息  
class User{  
    private String permission = "ViewAction" ;  
  
    public String getPermission() {  
        return permission;  
    }  
  
    public void setPermission(String permission) {  
        this.permission = permission;  
    }  
}  
  
public class proxy {  
    public static void main(String[] args) {  
  
        DoAction action =(DoAction) ProxyAction.getInstance(new DoActionImpl());  
        action.AddAction();  
    }  
} 
 

你可能感兴趣的:(java)