How To Get JSF Managed Bean Programmatically By Type

Sample describes how to get JSF Managed Bean programmatically by Type

1. Base parent class for all Managed Beans

public abstract class BaseBean implements Serializable {

	private static final long serialVersionUID = 1L;
	.....
	public <T extends BaseBean> T getManagedBeanByType(final Class<T> clazz) {
		String name = null;
		try {
			name = (String) clazz.getDeclaredField("BEAN_NAME").get(null);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		FacesContext context = FacesContext.getCurrentInstance();
		return clazz.cast(context.getApplication().evaluateExpressionGet(
				context, "#{" + name + "}", clazz));
	}
}

2. Managed Bean Definition

@ManagedBean(name = ChildBean.BEAN_NAME)
public class ChildBean extends BaseBean {
	...
	public final static String BEAN_NAME = "childBean";

	public void childBeanMethod()
	{
	....
	}
}

3. Use of getManagedBeanByType in another Managed Bean

....
	getManagedBeanByType(ChildBean.class).childBeanMethod();
....

Requirement Engineering, Business Analysis, Agile, Analysis and Design with UML, Java/J2EE, Liferay, Javascript, Embedded C++, MDD, Executable UML, Project Management


© 2017 JULIUSURBAN.NET