3

Is there any way to access the annotations of the parameters on a lambda expression? I don't see the parameters when I attempt to introspect the lambda class at runtime:

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.function.Consumer;


@Retention(RetentionPolicy.RUNTIME)
@interface TestAnnotation {

}

public class ParameterNameTest {
    static void printParameterName(Consumer<String> consumer) {
        System.out.println(consumer.getClass().getDeclaredMethods()[0].getParameterAnnotations()[0][0]);
    }


    public static void main(String[] args) {

        // a regular anonymous inner class
        Consumer<String> consumer0 = new Consumer<String>() {
            @Override public void accept(@TestAnnotation String foo) {

            }
        };

        // a lambda expression
        Consumer<String> consumer1 = (@TestAnnotation String foo) -> {

        };

        //prints @TestAnnotation()
        printParameterName(consumer0);

        //throws ArrayIndexOutOfBoundsException because the parameter does not exist
        printParameterName(consumer1);
    }
}
Stuart Marks
  • 127,867
  • 37
  • 205
  • 259
SamBeran
  • 1,944
  • 2
  • 17
  • 24

0 Answers0