I'm looking at collecting all the method parameters of generic methods in an Object[] array for logging purposes. I'm aware that this is better achieved using aspects, but am disallowed from using it and am looking for a pure reflection based approach if possible
To clarify, Assuming a method call
class A {
foo(int a, Object b){
}
}
Given an object instance of A, is it possible within the 'foo' method to dynamically determine the arguments that were passed? I cant seem to find any API in java.lang.reflect or annotations to determine this.
EDIT: I currently use the implementation below for logging. However it's tedious to collect all method params in an array before calling it and was wondering if this could be inferred somehow. I'm looking for any suggestion/library other than aspects
private static final ConcurrentMap<Class, Method[]> METHODS = new ConcurrentHashMap<Class, Method[]>();
protected void log(Class clazz, String methodName, Object[] args) {
Method[] methods = METHODS.get(clazz);
if (methods==null){
methods = clazz.getDeclaredMethods();
METHODS.put(clazz, methods);
}
for(Method method:methods){
if (method.getName().equals(methodName)){
StringBuilder builder = new StringBuilder(methodName + '(');
int i=0;
for (Class type:method.getParameterTypes()){
builder.append(type.getSimpleName())
.append(" [")
.append(args[i++])
.append("] ,");
}
String str = StringUtils.removeEnd(builder.toString(), ",") + ")";
LoggerFactory.getLogger(clazz).info(str);
}
}
}