Question

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;
}
Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top