Short version:
I need to find a way in Java to locate the previous Method
in the call stack (note the capital 'M' in Method--I need the actual java.lang.reflect.Method
object).
Background:
I'm working on an extension to the Google Guava Preconditions.checkNotNull(...)
concept that will allow the programmer to simultaneously check ALL of the parameters for null, and construct an NPE based on the parameter names of the calling method. For example:
public class MyClass
{
public void myMethod(Object arg1, Integer arg2, String arg3)
{
MyPreconditions.checkAllNotNull(arg1, arg2, arg3);
}
}
So if the first argument was null, then the NPE might read arg1 cannot be null (MyClass:myMethod(Object, Integer, String)
I've already worked out how to get the calling Class
and I can get the parameter names via the Spring LocalVariableTableParameterNameDiscoverer
(or via the Paranamer library) one I have the Method
. The only part that I can't figure out is how to get Method
itself.
I'm aware that you can use the stack trace to get the method name, but that doesn't help if the method is overridden. Is there a way (even with internal com.sun classes) to get the actual stack? Alternatively, I can get the line number for the calling method, so is there a way to find the line number of a Method
as retrieved from the Class
object?