Update
I am assuming from the question that you are looking for the name of argument
passed to that method
, rather than name of parameter
received by the method.
As the object
passed could be null
so there can be no information sent to the method in case of argument
.
As the reference variable is just name carrying the address to actual Object
. I don't think JVM
cares about the argument
name.
And there would be time when you send an Object
like this methodName(new Object())
. In this scenario there is no argument
name But only the address of the Object
passed to the methodName
.
So given below code gives you some option ways to meet your requirement.
The solution mentioned in your question is actually in use in some ways by a library developed by Google
, especially for NullPointerException
public class TestDriveException {
public static void main(String[] args) {
MyItem myItem = null;
validate(myItem);
}
public static void validate(MyItem myItem) {
if (myItem == null) {
throw new MyArgumentException("myItem is null");
}
}
private class MyItem {
String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
private static class MyArgumentException extends NullPointerException {
public MyArgumentException(String s) {
super(s);
}
}
}
Something like this can be done, or I am not sure about the argument as its just a name holding the address of the Object
. For any sort of information to be passed from the Object
, it has to be non null
.
the other thing which you have suggested in the question can be used as well,
public static void validate(MyItem myItem, String argumentValue) {
if (myItem == null) {
throw new MyArgumentException(argumentValue+" is null");
}
}