Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8281462

Annotation toString output for enum not reusable for source input

XMLWordPrintable

    • 9
    • b10
    • Verified

      As a follow up to JDK-8162817, if an enum used in an annotation has overridden `toString()` to return something other than `name()`, the output of the annotation's `toString()` method will not be reusable for source input.

      Given the following example application:

      -------------------------------------------------------------------------
      package example;

      import java.lang.annotation.Retention;
      import java.lang.annotation.RetentionPolicy;
      import java.lang.reflect.Method;

      public class Example {

      enum Color {
      RED, GREEN, BLUE;

      public String toString() {
      return name().toLowerCase();
      }
      }

      @Retention(RetentionPolicy.RUNTIME)
      @interface Colors {
      Color[] value();
      }

      @Colors({Color.RED, Color.BLUE})
      public static void main(String[] args) throws Exception {
      Method method = Example.class.getDeclaredMethod("main", String[].class);
      System.out.println(method.getAnnotation(Colors.class));
      }
      }
      -------------------------------------------------------------------------

      The output of the application on JDK 9 through JDK 17 is:

      @example.Example$Colors({red, blue})

      Whereas, we would expect the output to be:

      @example.Example$Colors({RED, BLUE})

      Or potentially using partially qualified enum constants as in:

      @example.Example$Colors({Color.RED, Color.BLUE})

      Or potentially using fully qualified enum constants as in:

      @example.Example$Colors({example.Example.Color.RED, example.Example.Color.BLUE})

      The cause for this is the fact that `Enum#toString()` is invoked instead of `Enum#name()` when generating the output of each enum constant in the `toString()` implementation of `Annotation`.

            darcy Joe Darcy
            sbrannen Sam Brannen
            Votes:
            0 Vote for this issue
            Watchers:
            5 Start watching this issue

              Created:
              Updated:
              Resolved: