- package graph;
- import java.lang.reflect.Method;
- import java.util.HashMap;
- import java.util.Map;
- import org.apache.log4j.Logger;
- import net.sf.cglib.proxy.Enhancer;
- import net.sf.cglib.proxy.MethodInterceptor;
- import net.sf.cglib.proxy.MethodProxy;
- public class MehtodProcessingTimesProxy implements MethodInterceptor {
- private Enhancer enhancer = new Enhancer();
- private Map<String, Long> map = new HashMap<String, Long>();
- Logger log = Logger.getLogger(MehtodProcessingTimesProxy.class);
- public Object intercept(Object o, Method method, Object[] args, MethodProxy proxy) throws Throwable {
- Long start = System.currentTimeMillis();
- Object result = proxy.invokeSuper(o, args);
- Long end = System.currentTimeMillis();
- if (!map.containsKey(method.toGenericString())) {
- map.put(method.toGenericString(), Long.valueOf(end - start));
- log.debug(method.toGenericString() + " " + (end - start) + "ms");
- }
- return result;
- }
- public Object ProxyFactory(Class clazz) {
- enhancer.setSuperclass(clazz);
- enhancer.setCallback(this);
- return enhancer.create();
- }
- }
- 下面是实例:
- package graph;
- public class ATest {
- public void method() {
- long j = 0;
- for (long i = 0; i < 1000000000; i++) {
- j += i;
- }
- }
- public void method1() {
- long j = 0;
- for (long i = 0; i < 1000000000; i++) {
- j += i;
- }
- }
- public void method2() {
- long j = 0;
- for (long i = 0; i < 1000000000; i++) {
- j += i;
- }
- }
- public void method3() {
- method();
- method1();
- method2();
- method();
- }
- public static void main(String[] args) {
- MehtodProcessingTimesProxy proxy = new MehtodProcessingTimesProxy();
- ATest t = (ATest) proxy.ProxyFactory(ATest.class);
- t.method();
- t.method1();
- t.method2();
- t.method();
- t.method3();
- }
- }