Annotation Interface MaxLength


Place on a method parameter of type String. Any string literals passed to that parameter will be checked at compile-time to be no longer than the maximum allowed length. Note that this cannot check dynamically generated string values - it is strongly recommended to pair this annotation with a runtime check to cover cases where dynamic values are used.

Errors generated by this annotation cannot be suppressed.

void acceptString(@MaxLength(5) String str) {
  if (str.length() > 5) {
    throw new IllegalArgumentException("String is too long");
  }
  // ...
}

acceptString("12345"); // OK - length is 5
acceptString("123456"); // Compile-time error: length is 6
acceptString("123" + "456"); // Compile-time error: length is 6
acceptString(" ".repeat(16)); // Runtime error - string argument is not a literal
  • Required Element Summary

    Required Elements
    Modifier and Type
    Required Element
    Description
    int
    The maximum allowable length of string literals passed to the annotated parameter.
  • Element Details

    • value

      int value
      The maximum allowable length of string literals passed to the annotated parameter. Must be a positive integer.
      Returns:
      The maximum length of allowed strings.