使用常量字符串作为Enum构造函数参数

时间:2016-02-02 02:47:00

标签: java enums

我尝试编写REST端点以根据人员类型返回数据。工作人员根据他们在组织中的角色进行分类,如此。

public enum StaffType {
    ADMIN("Admin"),
    CASUAL("Casual"),
    CORE("Core"),
    MANAGEMENT("Management");

    private String type;

    StaffType(String type) {
        this.type = type;
    }

    public String getType() {
        return type;
    }
}

现在在我的REST端点中,我无法明确地引用这些枚举。我能做的最好的是参考与每个相关联的字符串文本,例如。 "联系"或"休闲"。

@RequestMapping(value = "/staff", method = RequestMethod.GET)
public ResponseEntity getStaff(
             @RequestParam(value = "", required = false, defaultValue = "Admin")
                      StaffType staffType) {

但我不喜欢在两个地方直接链接时重复相同的字符串,并且应该始终相同。

所以我想到了创建一个常量,并且都引用了该类中的常量

public class Constants {
    public static String ADMIN = "Admin";
    public static String CASUAL = "Casual";
    ...
}

public enum StaffType {
    ADMIN(Constants.ADMIN),
    CASUAL(Constants.CASUAL),
    ...
}
@RequestMapping(value = "/staff", method = RequestMethod.GET)
public ResponseEntity getStaff(
             @RequestParam(value = "", required = false, defaultValue = Constants.ADMIN)
                      StaffType staffType) {

我的问题是,是否有更好,更广泛接受的方法来解决这个问题?或者这是一个合适的解决方案吗?

1 个答案:

答案 0 :(得分:1)

看起来适合我。 但是我会将字符串常量放在枚举类中,这是将它们放在枚举常量中的更好位置。要绕过“无前向引用”约束,可以将它们放在枚举中的静态内部类中:

public enum StaffType {
    ADMIN(Strings.ADMIN), 
    CASUAL(Strings.CASUAL);

    public static class Strings {
        public static String ADMIN = "Admin";
        public static String CASUAL = "Casual";
    }

    // ...
}
@RequestMapping(value = "/staff", method = RequestMethod.GET)
public ResponseEntity getStaff(
        @RequestParam(value = "", required = false, defaultValue = StaffType.Strings.ADMIN)
                      StaffType staffType) {
相关问题