从Scala(Play Framework)中的String字段获取Java枚举中的Map [enum,String]?

时间:2013-09-18 16:19:53

标签: java scala enums playframework playframework-2.1

我有以下Java枚举:

public enum CertificateType {

    EMAIL("Email"),

    NATURAL_QUALIFIED("Qualified"),

    PSEUDONYMOUS_QUALIFIED("Qualified");

    public final String NAME;

    private CertificateType( final String name ) {
    this.NAME = name;
    }

}

我想要做的是将该枚举转换为Map [enum as String,enum.NAME]以在Play Framework @select函数中使用。通过enum as String,我的意思是“EMAIL”,或“NATURAL_QUALIFIED”

对于对象列表,我会使用.map函数,如下所示:

Organization.all.map(org => (org.id.toString, org.name))(collection.breakOut)

但我认为我不能修改它以使用枚举。

我该如何做到这一点?

编辑:注释与Scala无关,但是是Play的ORM注释。上面的代码是Java枚举。按枚举值,我的意思是每个枚举,如EMAIL,NATURAL_QUALIFIED等。

示例键=>值对将是“EMAIL”=>“电子邮件”

编辑2 :为清晰起见,我删除了枚举上的注释。

2 个答案:

答案 0 :(得分:2)

CertificateType.values.map(e => (e.name -> e.NAME) ).toMap

答案 1 :(得分:0)

剥离我不熟悉的scala部分,你能不能做这样的事情吗?

public enum CertificateType {
    EMAIL("Email"),

    NATURAL_QUALIFIED("Qualified"),

    PSEUDONYMOUS_QUALIFIED("Qualified");

    public final String NAME;
    private static Map<CertificateType, String> map = new HashMap<CertificateType, String>();

    private CertificateType( final String name ) {
        this.NAME = name;
        map.put(this, this.NAME);
    }

    public Map<CertificateType, String> getMap()
    {   //Return a copy so that any modifications a 
        //user might make won't propagate back to the stored map
        return new HashMap<CertificateType, String>(map);
    }
}