How can one obtain objects of the following types from specific instances of their represented language feature in the code:
- java.lang.reflect.Executable
- java.lang.reflect.Parameter
Ideally the providing method would be a caller of the obtaining method or the obtaining method itself.
Note that I have found two kinds of answers on SO:
- how to get a Parameter from a given Executable object (trivial!)
- how to get the name (not signature!) of a method from the call stack
Neither helps to obtain the Parameter to a particular method whose name is not unique.
Consider in particular how this answer and this one to similar questions gloss over the selection of the desired method.
Now, there exists Class.getMethod(String, Class<?>... types)
but it does not seem that one could generate the "types" parameter automatically from an existing method definition?
Use case:
public class MyAssertions
{
private static final String DEFAULT_MESSAGE_NOT_NULL = "Parameter must not be null: ";
/* Ideal. */
public static void notNull(Object ref, Parameter param)
{
if(ref == null)
throw new IllegalArgumentException(DEFAULT_MESSAGE_NOT_NULL + param.getName());
}
/* Still okay. */
public static void notNull(Object ref, Executable caller, int param)
{
if(ref == null)
throw new IllegalArgumentException(DEFAULT_MESSAGE_NOT_NULL
+ caller.getParameters()[param].getName());
}
/* Hell no! */
public static void notNull(Object ref, Class<?> caller, String method, Object[] paramTypes, int param)
{
if(ref == null)
throw new IllegalArgumentException(DEFAULT_MESSAGE_NOT_NULL
+ caller.getMethod(method, paramTypes)
.getParameters()[param].getName());
}
}
Method
object if performance doesn’t matter, but if all you want, is the parameter name, and you’re even introducing a dependency to the parameter position at the same time, it doesn’t make much sense. Isn’tObjects.requireNonNull(myParam, "myParam")
cleaner and simpler thanMyAssertions.notNull(myParam, 42)
? Especially, as the latter only provides a name if the method has been compiled with a special option to retain method parameter names?