如何在f:selectItems中为枚举创建和使用泛型bean? [英] How to create and use a generic bean for enums in f:selectItems?
问题描述
我有这个签名的泛型类:
I have generic class with this signature:
public abstract class EnumListBean<E extends Enum<E>> {
public List<E> getEnumList() {
//implementation details
}
}
目前,我必须定义一个空子类才能访问具体的泛型参数的enumList属性:
Currently I have to define a empty subclass in order to access the enumList property for a concrete generic parameter:
@ManagedBean
@ApplicationScoped
public class ItemRarityBean extends EnumListBean<Item.Rarity>{
}
这可以访问属性,例如:
This makes its possible to access the property e.g:
<f:selectItems value="#{itemRarityBean.enumList}" var="rarity"
itemLabel="#{rarity.readableName}" itemValue="#{rarity}" />
我想知道是否真的必须声明一个派生bean,但是不能直接通过bean直接访问泛型类:
Im wondering whether one really have to declare a deriving bean but cant access the generic class as bean directly:
<f:selectItems value="#{enumListBean<Item.Rarity>.enumList}" var="rarity"
itemLabel="#{rarity.readableName}" itemValue="#{rarity}" />
推荐答案
你不能在EL中使用泛型。 EL是基于反射的运行时语言。你知道,泛型只在复习期间才可用,而不是在运行期间。
You can't use generics in EL. EL is a runtime language based on reflection. You know, generics is only available during compiletime, not during runtime.
为了您的特定目的,可能更容易使用 OmniFaces < o:importConstants>
。
For your particular purpose, it's likely easier to use OmniFaces <o:importConstants>
.
<o:importConstants type="com.example.Item$Rarity" var="Rarity" />
...
<h:selectOneMenu>
<f:selectItems value="#{Rarity}" />
</h:selectOneMenu>
( var
属性不是强制性的,但是否则需要将其引用为#{Item $ Rarity}
,这不完全可读;如果您的 Rarity
枚举是独立的枚举而不是内部枚举,那么你可以使用 type =com.example.Rarity
)
(the var
attribute is not mandatory, but you'd otherwise need to reference it as #{Item$Rarity}
which is not exactly nicely readable; if your Rarity
enum were a standalone enum and not an inner enum, then you could just use type="com.example.Rarity"
)
它被设计为 Map< String,Rarity>
,而不是列表&Rity> ;
左右。因此,如果你想要访问在变种的单独项目
的属性< F:selectItems的>
,这样就可以访问特定的枚举方法,那么您需要显式迭代 Map#values()
(这将需要EL 2.2支持)。
It's by design treated as a Map<String, Rarity>
, not a List<Rarity>
or so. So if you intend to access the individual items in the var
attribute of <f:selectItems>
, so that you can access specific enum methods, then you'd need to explicitly iterate over Map#values()
(which would require EL 2.2 support).
<h:selectOneMenu>
<f:selectItems value="#{Rarity.values()}" var="rarity" itemValue="#{rarity}" itemLabel="#{rarity.readableName}" />
</h:selectOneMenu>
这篇关于如何在f:selectItems中为枚举创建和使用泛型bean?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!