I have a Java function called testForNull
public static void testForNull(Object obj) { if (obj == null) { System.out.println("Object is null"); } } I use it to test multiple objects to ensure they are not null. But, I am unable to tell the name of the variable that way.
For eg. if I say
testForNull(x); testForNull(y); testForNull(z); I cannot tell which of the three lines caused the "Object is null" output. Of course, I can simply add another parameter to the function and have something like
testForNull(x, "x"); testForNull(y, "y"); testForNull(z, "z"); But I want to know whether it is possible to deduce the name of the variable without passing it explicitly. Thanks.
testForNull(new Object()); // I have NO name!Preconditions.checkNotNullfrom Google's Guava libraries.Preconditions.checkNotNull(x);will throw a NullPointerException whenxisnull. You can use the variant that takes a string to make it easy to see which variable failed.Preconditions.checkNotNull(x, "x");. Of course, exceptions fail fast.