Java注释:在另一个字段中使用字段值

Java注释:在另一个字段中使用字段值,java,java-annotations,Java,Java Annotations,我有以下注释类 public @interface Size { int min() default 1; int max() default 100; String message() default "Age between min - max"; } 这里是默认的message()我想要默认值min()和max()。只需编写String message()默认值“年龄介于”+min()+“-”+max()之间”在这里不起作用。有什么直接的方法吗 编辑1: 我也有个人课 pub

我有以下注释类

public @interface Size {
  int min() default 1;
  int max() default 100;
  String message() default "Age between min - max";
}
这里是默认的
message()
我想要默认值
min()
max()
。只需编写
String message()默认值“年龄介于”+min()+“-”+max()之间”在这里不起作用。有什么直接的方法吗

编辑1: 我也有个人课

public class Person {

  @Size(max = 10)
  private String name;

  @Size(min = 18, message = "Age can not be less than {min}")
  private int age;

  public Person(String s, int i) {
    this.name = s;
    this.age = i;
  }
}
现在,可以在这里设置
min()
max()
值。因此,如果用户输入错误,
消息()

编辑2: 正如尼古拉斯所希望的那样。这里是验证输入和打印错误消息的
AnnonatedValidator

public class AnnotatedValidator {

public static void validate(Person p, List<ValidationError> errors) {

    try {
        Field[] fields = p.getClass().getDeclaredFields();
        for(Field field : fields) {
            if(field.getType().equals(String.class)){
                field.setAccessible(true);
                String string = (String)field.get(p);

                Annotation[] annotationsName = field.getDeclaredAnnotations();
                for (Annotation annotation : annotationsName){
                    if (annotation instanceof Size){
                        Size size = (Size) annotation;
                        if (string.length() < size.min() || string.length() > size.max()) {
                            error(size, errors);
                        }
                    }
                }

            } else if (field.getType().equals(int.class)) {
                field.setAccessible(true);
                int integer = (Integer)field.get(p);

                Annotation[] annotationsAge = field.getDeclaredAnnotations();
                for (Annotation annotation : annotationsAge){
                    if (annotation instanceof Size){
                        Size size = (Size) annotation;
                        if (integer < size.min() || integer > size.max()) {
                            error(size,errors);
                        }
                    }
                }
            }
        }

    }catch (IllegalAccessException e) {
        e.printStackTrace();
    }
}

public static void print(List<ValidationError> errors) {
    for (int i = 0; i < errors.size(); i++){
        System.out.println("Errors: " + errors.get(i).getError());
    }
}

public static void error (Size size, List<ValidationError> errors) {
    String error = size.message();
    if (!error.equals(null)) {
        if (error.contains("min")) {
            error = error.replace("min", ""+size.min());
        }
        if (error.contains("max")){
            error = error.replace("max", ""+size.max());
        }
    }

    ValidationError v = new ValidationError();
    v.setError(error);
    errors.add(v);
}
}
public类AnnotatedValidator{
公共静态无效验证(人员p,列出错误){
试一试{
Field[]fields=p.getClass().getDeclaredFields();
用于(字段:字段){
if(field.getType().equals(String.class)){
字段。setAccessible(true);
String=(String)field.get(p);
Annotation[]annotationsName=field.getDeclaredAnnotations();
用于(注释:注释名称){
if(注释实例的大小){
大小=(大小)注释;
if(string.length()size.max()){
误差(大小、误差);
}
}
}
}else if(field.getType().equals(int.class)){
字段。setAccessible(true);
整型=(整型)字段.get(p);
Annotation[]annotationsAge=field.getDeclaredAnnotations();
用于(注释:annotationsAge){
if(注释实例的大小){
大小=(大小)注释;
if(整数size.max()){
误差(大小、误差);
}
}
}
}
}
}捕获(非法访问例外e){
e、 printStackTrace();
}
}
公共静态无效打印(列表错误){
对于(int i=0;i

ValidationError
是另一个只保存错误的类。

否,
String
类型的
默认值必须是常量表达式,因为

如果元素类型不相称,则为编译时错误 使用元素值。元素类型
T
与 元素值
V
当且仅当下列任一项为真时:

  • [……]
  • T
    不是数组类型,
    V
    的类型与赋值兼容 (§5.2)带有
    T
    ,并且:
    • [……]
    • 如果
      T
      是基本类型或
      String
      ,则
      V
      是常量表达式(§15.28)
调用另一个注释元素不是常量表达式

您需要在管理注释使用的组件中处理此问题。将
default
消息声明为一些特殊值

String message() default "REPLACE_ME";
然后在构造消息时检查它。比如说

Field field = ... // get 'age' field
Size size = field.getAnnotation(Size.class);
if (size != null) {
    String message = size.message();
    if (message.equals("REPLACE_ME")) {
        message = "Age between " + size.min() + " - " + size.max() + "."; 
    }
}
int min = size.min();
int max = size.max();
// if field is of type int
int value = field.getInt(instance);
if (value > max || value < min) {
    throw new ConstraintViolationException(message);
}
字段=…//获取“年龄”字段
Size=field.getAnnotation(Size.class);
如果(大小!=null){
字符串消息=size.message();
if(message.equals(“REPLACE_ME”)){
message=“年龄介于”+size.min()+“-“+size.max()+”;
}
}
int min=size.min();
int max=size.max();
//如果字段的类型为int
int value=field.getInt(实例);
如果(值>最大值| |值<最小值){
抛出新的ConstraintViolationException(消息);
}

注释值应为常量,您不能调用min/max。您应该在打印消息的代码中对其进行管理,因为只有常量才应作为默认值,如前所述。显示显示显示消息的代码如果您希望通过输入来改进消息以获得预期结果,则应使用
{name}在{min}-{max}
之间作为默认消息,将
{min}
{max}
分别替换为
size.min()
size.max()
,将
{name}
替换为
field.getName()
我也这样做了。我替换了min和max。