我正在尝试编写一个 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) {
我的问题是,是否有更好、更广泛接受的方法来解决这个问题?或者这是一个合适的解决方案?
最佳答案
看起来很适合我。 不过,我会将字符串常量放在枚举类中,这是放置它们的更好位置,因为它们与枚举常量属于一起。为了绕过“无前向引用”约束,您可以将它们放在枚举内的静态内部类中:
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) {
关于java - 使用常量字符串作为 Enum 构造函数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35144159/