Skip to content

Instantly share code, notes, and snippets.

@thejibz
Last active November 27, 2015 16:26
Show Gist options
  • Save thejibz/e194c590ac1ba92061a8 to your computer and use it in GitHub Desktop.
Save thejibz/e194c590ac1ba92061a8 to your computer and use it in GitHub Desktop.
Generate a ternary null checking for a chained call.
/**
* Generate a ternary null checking for a chained call.
* a.getB().getC().getD().getE()
* =>
* (a != null
&& a.getB() != null
&& a.getB().getC() != null
&& a.getB().getC().getD() != null
&& a.getB().getC().getD().getE() != null)
?
a.getB().getC().getD().getE() : ""
*/
public class TernaryNullChecking {
public static void main(String [ ] args) {
String result;
String str = "a.getB().getC().getD().getE()";
String[] strSplitted = str.split("\\.");
result = "(" + strSplitted[0] + " != null";
String s = strSplitted[0] + ".";
for (int i = 1; i < strSplitted.length; i++) {
s = s + strSplitted[i];
result = result + " \n&& " + s + " != null";
s = s + ".";
}
result = result + ") \n?\n " + str + " : " + "\"\"";
System.out.println(result);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment