如何为给定对象创建枚举

时间:2014-04-02 13:31:54

标签: java enums

我有一个名为SparqlResource.java的类,在类中我实例化了四个这样的对象 -

public static final SparqlResource MARK_SIMPLE_TYPE = new SparqlResource("ldmext/MarkSimpleType.rq");
public static final SparqlResource FORTRESS_HAS_ENVOY = new SparqlResource("ldmext/FortressHasEnvoy.rq");
public static final SparqlResource FORTRESS_HAS_GUARD = new SparqlResource("ldmext/FortressHasGuard.rq");
public static final SparqlResource FORTRESS_HAS_PORT = new SparqlResource("ldmext/FortressHasPort.rq");

现在来自另一个类 - JenaLanguageConstructor.java,我正在引用这样的对象 -

runOneQuery(SparqlResource.MARK_SIMPLE_TYPE, true);
runOneQuery(SparqlResource.FORTRESS_HAS_ENVOY, true);
runOneQuery(SparqlResource.FORTRESS_HAS_GUARD, true);
runOneQuery(SparqlResource.FORTRESS_HAS_PORT, true);

现在我的问题是有什么方法可以使用枚举来实现这一点,如果是这样,那么任何人都可以给我一个示例代码,我可以用来创建枚举?

2 个答案:

答案 0 :(得分:1)

好吧,创建一个枚举并不会那么难:

enum MyEnum {
  VALUE1("name 1"),
  VALUE2("name 2");

  private String name;

  private MyEnum(String n) {
    name = n;
  }

  //whatever else you need
}

答案 1 :(得分:1)

public enum SPARQLENUM {
    MARK_SIMPLE_TYPE("ldmext/MarkSimpleType.rq") ,
    FORTRESS_HAS_ENVOY("ldmext/FortressHasEnvoy.rq") ,
    FORTRESS_HAS_GUARD("ldmext/FortressHasGuard.rq") ,
    FORTRESS_HAS_PORT("ldmext/FortressHasPort.rq");

    private String value;

    private SPARQLENUM(String value) {
        this.value = value;
    }


    public String getValue(){
        return value;
    }


}

你可以这样称呼它:

SPARQLENUM.FORTRESS_HAS_ENVOY.getValue()

<强> EDITED

如果您需要SparqlResource对象,可以这样创建枚举:

public enum SPARQLENUM {
    MARK_SIMPLE_TYPE(new SparqlResource("ldmext/MarkSimpleType.rq")) ,
    FORTRESS_HAS_ENVOY(new SparqlResource("ldmext/FortressHasEnvoy.rq")) ,
    FORTRESS_HAS_GUARD(new SparqlResource("ldmext/FortressHasGuard.rq")) ,
    FORTRESS_HAS_PORT(new SparqlResource("ldmext/FortressHasPort.rq"));

    private SparqlResource value;

    private SPARQLENUM(SparqlResource value) {
        this.value = value;
    }


    public SparqlResource getValue(){
        return value;
    }


}