You can achieve the desired result using the Option template. This forces you to change the signature of the method, but basically, if your method returns some type T , it ensures that it has some non-zero value, and if it returns Option<T> , then it either has the value T or null.
Java 7 had a feature called zero security, but it was removed from the final release. You can do:
obj?.getA()?.getB()?.getC()?.getD()
In addition, Java 8 will add a function called Optional so you can do it safely.
In fact, if you really want to use this now, try the Null Object template. This means that instead of returning plain null you can return some default value that will not throw a NullPointerException. Although you need to add some changes to your getters
class Object { A getA() {
EDIT: If you want to do this, you can transfer it to some functional interface and then call it.
static boolean isNullResult(Callable call) throws Exception { try { return call.call() == null; } catch (NullPointerException npe) { return true; } }
Usage will be as follows:
isNullResult(new Callable<Integer>() { @Override public Integer call() throws Exception { return new A().getB().getC().getInt(); } });
This does not require a change in existing functionality.
mishadoff
source share