I've already known how to check integer range with help of AspectJ (see code below).

Question: But how should I calculate allowed range dynamically?

Code:

annotation:

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Range {
    int min();

    int max();
}

validation:

@Aspect
public class Validation {

    @Before("args(value) && @annotation(range)")
    public void checkRange(Object value, Range range) throws ValidationException {
        double number = ((Number) value).doubleValue();
        if (number < range.min() || number > range.max()) {
            throw new ValidationException("Invalid data! Range constraint violated!");
        }
    }
}

entity:

@Entity
@Table(name = "my_entity")
public class MyEntity {


  @Range(min = 2, max = 10) // I WANT TO CALCULATE THESE RANGES DYNAMICALLY!!!
  private int number;
}
有帮助吗?

解决方案

You can't set values of annotation attributes dynamically; they must be compile-time constants and are built into the code. You might be able to hack something together with tools such as CGLIB and runtime bytecode generation, but you'd probably be better off just writing the validation logic into the class's methods.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top