There is no such magic for the invoked method. Since you are passing values to the method, these arguments do not bear any information about their parameter roles. In fact, there is no guaranty that the values passed to validateParameters
are parameters in the callers context. You can, e.g. invoke it as validateParameters(Math.sin(2), null)
or validateParameters(bufferedReader.readLine())
and it’s not clear, what name the method should assume for its arguments, when it encounters null
. The simplest solution is to provide the parameter names explicitly:
private static String[] parameterNames={ "name", "address" };
public void parametersForValidation(String name,String address){
validateParameters(parameterNames, name, address);
}
private void validateParameters(String[] name, Object... values){
for(int ix=0; ix<name.length; ix++) {
if(values[ix]==null) {
throw new NullPointerException(name[ix]+" is mandatory");
}
}
}
For comparison, if you are using Java 8 and have compiled your code using the -parameters
option, the parameter names are available at runtime via Reflection, i.e. you can use
public void parametersForValidation(String name, String address) {
String[] names;
try {
names = Arrays.stream(getClass()
.getMethod("parametersForValidation", String.class, String.class)
.getParameters()).map(Parameter::getName).toArray(String[]::new);
}
catch(ReflectiveOperationException ex) { throw new AssertionError(ex); }
validateParameters(names, name, address);
}
private void validateParameters(String[] name, Object... values) {
for(int ix=0; ix<name.length; ix++) {
if(values[ix]==null) {
throw new NullPointerException(name[ix]+ " is mandatory");
}
}
}
which is obviously not simpler than just providing the names and exchanges the explicit list of names with an explicit list of the name and parameter types of the method to look up reflectively.