I was reading an article linked from a slashdot story, and came across this little tidbit:
Take the latest version of Java, which tries to make null-poi
If someone is looking for an alternative for old java versions, you can try this one I wrote:
/**
* Strong typed Lambda to return NULL or DEFAULT VALUES instead of runtime errors.
* if you override the defaultValue method, if the execution result was null it will be used in place
*
*
* Sample:
*
* It won't throw a NullPointerException but null.
*
* {@code
* new RuntimeExceptionHandlerLambda () {
* @Override
* public String evaluate() {
* String x = null;
* return x.trim();
* }
* }.get();
* }
*
*
*
* @author Robson_Farias
*
*/
public abstract class RuntimeExceptionHandlerLambda {
private T result;
private RuntimeException exception;
public abstract T evaluate();
public RuntimeException getException() {
return exception;
}
public boolean hasException() {
return exception != null;
}
public T defaultValue() {
return result;
}
public T get() {
try {
result = evaluate();
} catch (RuntimeException runtimeException) {
exception = runtimeException;
}
return result == null ? defaultValue() : result;
}
}