org.milyn.reflect.MethodInvocationProxyHandler Maven / Gradle / Ivy
/*
Milyn - Copyright (C) 2006 - 2010
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License (version 2.1) as published by the Free Software
Foundation.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU Lesser General Public License for more details:
http://www.gnu.org/licenses/lgpl.txt
*/
package org.milyn.reflect;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* Utility class for capturing method invocation statistics.
*
* Useful for testing.
*
* Note: Be careful how you use this class. It doesn't filter out
* recursive/internal method calls i.e. you could eat memory with this class
* if not carefull. Ideally, it should only log external Object invocations.
*
* @author [email protected]
*/
public class MethodInvocationProxyHandler implements InvocationHandler {
private T object;
private List callList = new ArrayList();
private Map> callMap = new LinkedHashMap>();
public MethodInvocationProxyHandler(T object) {
this.object = object;
}
public T getObject() {
return object;
}
public T newProxy(Class[] interfaces) {
return (T) Proxy.newProxyInstance(MethodInvocationProxyHandler.class.getClassLoader(), interfaces, this);
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
logCall(method, args);
return method.invoke(object);
}
private synchronized void logCall(Method method, Object[] args) {
Exception thisCallStack = new Exception();
MethodCall methodCall = new MethodCall(callList.size(), thisCallStack, args);
callList.add(methodCall);
getCallList(method.getName()).add(methodCall);
}
/**
* Get the complete method call list.
*
* This is the list of method calls, ordered by the order in which the
* calls were made.
*
* @return Call list.
*/
public List getCallList() {
return callList;
}
/**
* Get the call list for a specific method.
*
* Overloaded method calls are bundled together.
*
* @param methodName The method name.
* @return Call list.
*/
public synchronized List getCallList(String methodName) {
List methodCallList = callMap.get(methodName);
if (methodCallList == null) {
methodCallList = new ArrayList();
callMap.put(methodName, methodCallList);
}
return methodCallList;
}
/**
* Get the call map.
*
* This is the {@link #getCallList() call list} sorted by method name. Overloaded method
* calls are bundled together.
*
* @return The call map.
*/
public Map> getCallMap() {
return callMap;
}
}