JDK-8246586 : java.lang.reflect.Parameter.getAnnotation doesn't take into account synthetic parameters
  • Type: Bug
  • Component: core-libs
  • Sub-Component: java.lang:reflect
  • Affected Version: 8,9,10,11,12,13,14,15
  • Priority: P4
  • Status: Closed
  • Resolution: Duplicate
  • Submitted: 2020-06-04
  • Updated: 2021-04-09
  • Resolved: 2021-04-09
The Version table provides details related to the release that this issue/RFE will be addressed.

Unresolved : Release in which this issue/RFE will be addressed.
Resolved: Release in which this issue/RFE has been resolved.
Fixed : Release in which this issue/RFE has been fixed. The release containing this fix may be available for download as an Early Access Release or a General Availability Release.

To download the current JDK release, click here.
JDK 17
17Resolved
Related Reports
Duplicate :  
Relates :  
Relates :  
Description
Sometimes synthetic parameters are added to the constructor (e.g. enum constructor). In this case, Parameter.getAnnotation doesn't take this into account. E.g. consider the following program:

import java.lang.annotation.*;
import java.lang.reflect.*;
import java.util.Arrays;

enum MyEnum {
  A(0.0, 0, "");

  MyEnum(@Foo("double annotated") double d, 
         int i, 
         @Foo("string annotated") String s) { }

  @Retention(RetentionPolicy.RUNTIME)
  @interface Foo {String value();}

  public static void main(String[] args) {
    Constructor<?> constructor = MyEnum.class.getDeclaredConstructors()[0];
    Parameter[] parameters = constructor.getParameters();
    Arrays.stream(parameters)
        .filter(p -> p.getType() == double.class)
        .forEach(p -> System.out.println(p.getAnnotation(Foo.class).value()));
  }
}

Expected output:

double annotated

Actual output:

string annotated

That's because compiler adds two synthetic parameters (enum constant name and ordinal), but RuntimeVisibleParameterAnnotations are not shifted by two (looks like it's specified so, by JVMS 4.7.18), and Parameter.getAnnotation doesn't take into account this shift either, so it reads the annotation of the wrong parameter.
Comments
Enum handling being addressed under JDK-8263763.
09-04-2021