1.private static class LoggingInvocationHandler  
2. implements InvocationHandler {  
3. final T underlying;  
4.public LoggingHandler(T underlying) {  
5. this.underlying = underlying;  
6. }  
7.public Object invoke(Object proxy, Method method,  
8. Object[] args) throws Throwable {  
9. StringBuffer sb = new StringBuffer();  
10. sb.append(method.getName()); sb.append("(");  
11. for (int i=0; args != null && i }  
12. System.out.println(sb);  
13. return ret;  
14. }  
15. }
 
  如果用日志代理包装 HashSet,并执行下面这个简单的测试程序:


1.Set s = newLoggingProxy(Set.class, new HashSet());  
2. s.add("three");  
3. if (!s.contains("four"))  
4. s.add("four");  
5. System.out.println(s);

 会得到以下输出:

1.add(three) -> true  
2. 
3.contains(four) -> false  
4. 
5.add(four) -> true  
6. 
7.toString() -> [four, three]  
8. 
9.[four, three]