表达式语言bean属性评估顺序

时间:2016-04-14 16:34:24

标签: jsf xpages el

给定一个托管bean(MyBean),它扩展了一个抽象类(AbstractMapModel),它本质上是Map的包装器:

AbstractMapModel类包含一个getValue(Object key)方法。

MyBean类包含一个getName()方法。

XPage的值为#{MyBean.name}。

我发现它调用MyBean.getValue(" Name")并忽略MyBean.getName()。我的问题是,这是正确的操作吗?

逻辑上,在尝试通用的getValue(" Name")之前,似乎应该尝试更具体的getName()。做一些研究,似乎如果getValue()返回null,它应该寻找一个特定的getter,即使我发现逻辑可疑,至少会得到正确的最终结果。然而,两者都没有发生。

我已使用以下代码解决了问题:

public Object getValue(final Object key) {
    /* Following code added to check for specific getter before performing getValues() */
    String propertyName = key.toString();
    propertyName = propertyName.substring(0, 1).toUpperCase() + propertyName.substring(1);
    Method method = null;
    try {
        method = this.getClass().getMethod("get" + propertyName, new Class[] {});
        if (method != null) {
            return method.invoke(this);
        }
    } catch (Exception e) {
        // Do nothing
    }
    try {
        method = this.getClass().getMethod("is" + propertyName, new Class[] {});
        if (method != null) {
            return method.invoke(this);
        }
    } catch (Exception e) {

    }
    /* --------------------------------------------- */
    return getValues().get(key);
}

似乎这种解决方法似乎不是必要的,所以我想知道我是否对正在发生的事情有一些基本的误解。或者,我应该有更好的方法吗?

1 个答案:

答案 0 :(得分:2)

尽管它经常有用,但EL并未遵循这样的“后备”策略。相反,它有一组循环遍历的接口 - MapDataObject等等(我不记得特定的顺序) - 如果对象与其中一个匹配,它将会完全使用该路线。你在那里用反射做的是我用来获得这种行为的相同策略。

相关问题