【发布时间】:2013-01-06 18:00:39
【问题描述】:
在 JSF 中,可以使用 EL 空操作符来渲染或不渲染组件
rendered="#{not empty myBean.myList}"
据我了解,该运算符既可以作为空检查,也可以检查列表是否为空。
我想对我自己的自定义类的一些对象进行空检查,我需要实现哪些接口或部分接口? 空算子兼容哪个接口?
【问题讨论】:
在 JSF 中,可以使用 EL 空操作符来渲染或不渲染组件
rendered="#{not empty myBean.myList}"
据我了解,该运算符既可以作为空检查,也可以检查列表是否为空。
我想对我自己的自定义类的一些对象进行空检查,我需要实现哪些接口或部分接口? 空算子兼容哪个接口?
【问题讨论】:
来自EL 2.2 specification(获取下方的“点击此处下载评估规范”):
1.10 空运算符 -
empty A
empty运算符是前缀运算符,可用于确定某个值是否为 null 或空。评估
empty A
- 如果
A是null,则返回true- 否则,如果
A为空字符串,则返回true- 否则,如果
A是一个空数组,则返回true- 否则,如果
A为空Map,则返回true- 否则,如果
A为空Collection,则返回true- 否则返回
false
因此,考虑到接口,它仅适用于 Collection 和 Map。在你的情况下,我认为Collection 是最好的选择。或者,如果它是类似 Javabean 的对象,则为 Map。无论哪种方式,在幕后,isEmpty() 方法都用于实际检查。在你不能或不想实现的接口方法上,你可以抛出UnsupportedOperationException。
【讨论】:
myBean 是null 呢? true/false 还会被返回还是会抛出异常?
使用 BalusC 的实现 Collection 的建议,我现在可以在扩展 javax.faces.model.ListDataModel 的 dataModel 上使用非空运算符隐藏我的 primefaces p:dataTable
代码示例:
import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import javax.faces.model.ListDataModel;
import org.primefaces.model.SelectableDataModel;
public class EntityDataModel extends ListDataModel<Entity> implements
Collection<Entity>, SelectableDataModel<Entity>, Serializable {
public EntityDataModel(List<Entity> data) { super(data); }
@Override
public Entity getRowData(String rowKey) {
// In a real app, a more efficient way like a query by rowKey should be
// implemented to deal with huge data
List<Entity> entitys = (List<Entity>) getWrappedData();
for (Entity entity : entitys) {
if (Integer.toString(entity.getId()).equals(rowKey)) return entity;
}
return null;
}
@Override
public Object getRowKey(Entity entity) {
return entity.getId();
}
@Override
public boolean isEmpty() {
List<Entity> entity = (List<Entity>) getWrappedData();
return (entity == null) || entity.isEmpty();
}
// ... other not implemented methods of Collection...
}
【讨论】: