2

Let's imagine a validation method call like this:

validate(foo, "foo");

where the second argument is the name of the variable provided in order to compose a meaningful exception message when the foo is null.

Is it possible in Java to retrieve the name of the provided value at runtime to avoid passing the name of the argument and make the method call look like in the following example?

validate(foo);
Pavel
  • 4,912
  • 7
  • 49
  • 69

1 Answers1

0

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");
    }
}    
Pankaj Nimgade
  • 4,529
  • 3
  • 20
  • 30