Search code examples
jsfjsf-2faceletscomposite-component

Get bean class from composite component


I have composite component:

<my:component value="#{bean.property1.property2}/>

From composite component I need to get class of bean.property1 to read its annotations. I do it by the following code:

ValueExpression valueExpression = expressionFactory.createValueExpression(FacesContext.getCurrentInstance().getELContext(),
                        "#{bean.property1}", Object.class);
Object bean = valueExpression.getValue(FacesContext.getCurrentInstance().getELContext());
Class<?> beanClass = bean.getClass();

This works well but if I use my:component from a facelet and pass bean as a parameter via ui:param this does not work because bean can't be resolved.

Probably I should use FaceletContext as ELContext instead of FacesContext.getCurrentInstance().getELContext():

FaceletContext faceletElContext = (FaceletContext) FacesContext.getCurrentInstance().getAttributes()
                    .get("javax.faces.FACELET_CONTEXT");

But this doesn't work on RENDER_RESPONSE phase (from encodeBegin method). It returns last used ELContext instead of actual context (I am not surprised :) ).

The goal is to get class of #{bean.property1} from my:component. How can I do it?


Solution

  • This is easy with RichFaces:

        ValueExpressionAnalayser analyser = new ValueExpressionAnalayserImpl();
        ValueDescriptor valueDescriptor = analyser.getPropertyDescriptor(context, valueExpression);
        Class<?> beanClass = valueDescriptor.getBeanType();
    

    This is ok for me.

    Also there is ValueExpressionAnalayzer in javax.faces.validator package but it is package private and can't be used.