'JSF: how to tell if a ValueExpression does not exist or actually its value is null?

FacesContext context = FacesContext.getCurrentInstance();
ELContext ctx = context.getELContext();
ValueExpression expression = context.getApplication().getExpressionFactory().createValueExpression(
    ctx, "#{foo111.bar}", String.class);
String value = expression.getValue(ctx);

The return value is null. Obviously foo111.bar does not exist. Is there a way to tell if an expression does not exist or actually its value is null.



Solution 1:[1]

The best way to do that would be to evaluate the expression. If it's a property expression this should be side-effect free (And smart EL Implementations cache this operation, so it should be cheap if invoked several times).

If it's a method expression it'll get more complicated. Invoking the function could cause a state mutation if all you're wanting to do is 'check for existence'. You could in theory get the base object and see if it exists without invoking the function, which gets you a little closer, but isn't a complete solution:

final ValueReference valueReference = valueExpression.getValueReference(getFacesContext().getELContext());
final Object base = valueReference.getBase();
... valueReference.getProperty();

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1