将常量字符串用作枚举构造函数参数

3

我正在尝试编写一个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端点中,我无法直接引用这些枚举。我能做的最好的办法是引用与每个枚举关联的字符串文本,例如“Admin”或“Casual”。

@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个回答

4

在我看来,这看起来很合适。 但是我会将字符串常量放在枚举类中,因为它们与枚举常量属于同一类别。为了避免“无前向引用”的限制,您可以将它们放在枚举内部的静态内部类中:

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) {

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接