码迷,mamicode.com
首页 > 编程语言 > 详细

Java 动态代理插入日志

时间:2016-04-24 06:21:00      阅读:240      评论:0      收藏:0      [点我收藏+]

标签:

被代理对象的接口

1 public interface IScoreService {
2     public void addScore(String s,String s1);
3 }

被代理的对象的实现

1 public class ScoreServiceImpl implements IScoreService{
2     int  score = 0;
3     public  List<Integer> sList = new ArrayList<Integer>();
4     
5     public void addScore(String s,String s1){
6         System.out.println(score+=3);
7         sList.add(score);
8     }
9 }

代理类

 1 public class LogHandler implements InvocationHandler {
 2     
 3     private Object targetObject;
 4     
 5     public Object createProxy(Object targetObject){
 6         this.targetObject = targetObject;
 7         return Proxy.newProxyInstance(targetObject.getClass().getClassLoader(), 
 8                 targetObject.getClass().getInterfaces(),
 9                 this);
10     }
11 
12     public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
13         
14         Object obj = null;
15         try {
16             beforeLog();
17             obj = method.invoke(targetObject, args);
18             afterLog();
19         } catch (Exception e) {
20             e.printStackTrace();
21         }
22         
23         
24         return obj;
25     }
26     
27     private void beforeLog(){
28         System.out.println("在之前调用");
29     }
30     
31     private void afterLog(){
32         System.out.println("在之后调用");
33     }
34 
35 }

测试类

1 public class TestHandler{
2     public static void main(String [] args){
3          IScoreService servcie = (IScoreService)logHandler.createProxy(new ScoreServiceImpl());
4          servcie.addScore("","");      
5     }
6 }

 

Java 动态代理插入日志

标签:

原文地址:http://www.cnblogs.com/94living/p/5426241.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!