我试图获取一些运行时信息来进行一些调试。有没有办法访问实际传递给方法的参数?
我知道调用类和方法,但不知道运行时的参数及其值。任何想法如何解决这个问题?提前谢谢。
到目前为止我的代码:
//get the class I wanna know something about out of the call history
StackTraceElement[] stacktrace = Thread.currentThread().getStackTrace();
String callerMethod = stacktrace[2].getMethodName();
//load the class to get the information
Class<?> c = Class.forName(stacktrace[2].getClassName());
Method[] methods = c.getMethods();
Class<?>[] parameters = methods[1].getParameterTypes();
//get the parameter data
(parameters[y].isArray()? parameters[y].getComponentType() : parameters[y]).getName();
//TODO: how about the parameter value at runtime?
代码必须是我将实现的所有类的通用代码。用法示例:
public class doClass() {
public void doSomething(Object o) {
//here comes my debug line
magicDebugger(level);
}
}
level
是激活console / db / file / mail输出或某些信息的开关/触发器
我希望得到以下输出(也许在magicDebugger类中有一些System.out.println):
[debug] caller: com.company.package.doClass.doSomething(Object o); value of o at runtime = java.lang.String "test"
答案 0 :(得分:1)
考虑使用反射。这应该提供你正在寻找的东西。
答案 1 :(得分:1)
你可以使用http://docs.oracle.com/javase/6/docs/api/java/lang/reflect/Proxy.html 用于执行该操作的代理类或AspectJ框架