-
Notifications
You must be signed in to change notification settings - Fork 6
/
ProxyInterceptor.java
65 lines (54 loc) · 1.85 KB
/
ProxyInterceptor.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/**
* Joice
* Copyright (c) 1995-2017 All Rights Reserved.
*/
package cn.tauren.framework.aop.api;
import java.lang.reflect.Method;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.InvocationHandler;
/**
* 代理拦截模板类
* <p>客户端继承此类,并选择覆盖<code>before</code>, <code>after</code>, <code>exception</code方法实现前置和后置增强</p>
* @author HuHui
* @version $Id: ProxyInterceptor.java, v 0.1 2017年11月22日 上午9:21:10 HuHui Exp $
*/
public abstract class ProxyInterceptor {
/**
* 前置增强
*/
protected void before(Class<?> targetClass, Method method, Object[] args) {
}
/**
* 后置增强
*/
protected void after(Class<?> targetClass, Method method, Object[] args) {
}
/**
* 异常
*/
protected void exception(Class<?> targetClass, Method method, Object[] args, Throwable e) {
}
/**
* 生成代理对象
* @param targetClass 被代理对象的类型(类或接口)
* @param target 被代理对象实例
* @return 代理对象
*/
@SuppressWarnings("unchecked")
public <T> T newProxyInstance(final Class<T> targetClass, final Object target) {
return (T) Enhancer.create(targetClass, new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
before(targetClass, method, args);
Object ret = null;
try {
ret = method.invoke(target, args);
} catch (Exception e) {
exception(targetClass, method, args, e);
}
after(targetClass, method, args);
return ret;
}
});
}
}