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);
    }
}
0

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.