I know I can find out if a variable is null in Java using these techniques:
(var==null)
-> too much worktry { ... } catch (NullPointerException e) { ...}
-> it tells me what line is throwing the exceptionConsider this line of code:
if (this.superSL.items.get(name).getSource().compareTo(VIsualShoppingList.Source_EXTRA)==0) {
I would like to know if there's a generic way to find out programatically what variable (not just the line) is throwing the NullPointerException in a certain area of code. In the example, knowing that
Since it's possible to cause a null pointer exception without even involving a variable:
throw new NullPointerException();
I would have to say that there is no generic way to pin down a null pointer exception to a specific variable.
Your best bet would be to put as few as possible statements on each line so that it becomes obvious what caused the null pointer exception. Consider refactoring your code in the question to look something like this:
List items = this.superSL.items;
String name = items.get(name);
String source = name.getSource();
if (source.compareTo(VIsualShoppingList.Source_EXTRA) == 0) {
// ...
}
It's more lines of code to be sure. But it's also more readable and more maintainable.