我们有一个我们构建的注释,用于验证方法的输入。像这样:
@InputValidation(paramName = "foo", regularExpression = RegularExpressionConstants.FOO_REG_EX)
我们的 RegularExpressionConstants
类有很多不同的字符串常量,它们都代表不同的正则表达式。这个类开始看起来很乱,所以我开始尝试用使其更容易阅读的方法来整理它等等。所以这个类现在看起来像这样:
public static final String FOO_REG_EX = alphanumericWithRange(1, 16);
public static final String BAR_REG_EX = alphanumericWithRange(2,4);
private static String alphanumericWithRange(int lowerLimit, int upperLimit) {
"[a-zA-Z0-9]{" + lowerLimit + "," + upperLimit + "}";
}
RegularExpressionConstants 类编译,但注释不再编译。错误是 Attribute value must be constant
。在查看了 StackOverflow 上的一些相关问题后,我明白了为什么会这样。我主要想知道是否有任何方法可以在不引起此问题的情况下在常量类中实现我想要的整洁度?还是我只需要处理大量困惑的常量?
最佳答案
您可以使用枚举代替字符串常量列表:
@interface InputValidation {
RegularExpressionConstants regularExpression() default
RegularExpressionConstants.FOO_REG_EX;
}
使用枚举还允许在定义模式的地方移动 name
元数据
enum RegularExpressionConstants {
FOO_REG_EX("foo", alphanumericWithRange(1, 16)),
BAR_REG_EX("bar", alphanumericWithRange(2,4));
private final String name;
private final String pattern;
private RegularExpression(String name, String pattern) {
this.name = name;
this.pattern = pattern;
}
public String getName() {
return name;
}
public String getPattern() {
return pattern;
}
private static String alphanumericWithRange(int lowerLimit, int upperLimit) {
return "[a-zA-Z0-9]{" + lowerLimit + "," + upperLimit + "}";
}
}
并且可以使用枚举应用注释:
@InputValidation(regularExpression=RegularExpressionConstants.FOO_REG_EX)
在注解处理的地方,调用就够了:
String pattern = field.getAnnotation(InputValidation.class)
.regularExpression()
.getPattern();
关于java - 有什么办法可以避免这个 "Attribute value must be constant"错误吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52253900/