Skip to content

Enum value extraction from annotation no longer works correctly in Java 17+Β #134

@xcesco

Description

@xcesco

🐞 Issue: Enum value extraction from annotation no longer works correctly in Java 17+

Description

In our annotation processor, we previously used the following logic to extract the value of an enum attribute from an annotation:

if (value.indexOf(".") >= 0)
    result.value0 = value.substring(value.lastIndexOf(".") + 1);

This worked correctly under Java 8, where AnnotationValue.toString() returned the fully qualified name of the enum constant (e.g., com.example.XmlType.ATTRIBUTE). However, starting with Java 11 and confirmed in Java 17+, this behavior has changed.


πŸ” Analysis

  • In Java 8:
    AnnotationValue.toString() returned the fully qualified name of the enum constant.
    Example:

    com.example.XmlType.ATTRIBUTE
  • In Java 17+:
    AnnotationValue.toString() returns only the simple name of the constant:

    ATTRIBUTE

As a result, the old logic relying on the presence of "." to extract the enum name no longer works as expected.


βœ… Proposed Solution

Option 1: Backward-compatible parsing logic

String valueStr = value.toString();
if (valueStr.contains(".")) {
    result.value0 = valueStr.substring(valueStr.lastIndexOf(".") + 1);
} else {
    result.value0 = valueStr;
}

Option 2: More robust approach using VariableElement

Object actualValue = value.getValue();
if (actualValue instanceof VariableElement) {
    result.value0 = ((VariableElement) actualValue).getSimpleName().toString();
}

This second option avoids relying on the potentially fragile toString() output and instead leverages the standard annotation processing API.


🧩 Notes

  • This behavior change is not officially documented, so relying on toString() is inherently brittle.
  • The VariableElement approach is recommended for long-term robustness and forward compatibility with future Java versions.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions