Will it be possible to annotate lambda expression in Java 9?

Markus Weninger :

This question is now over 3 years old and specifically addressed Java 8, with the accepted answer also citing the Java SE 8 Final Specification.

I would be interested if something regarding this question will change in Java 9: Is there any way to annotate a lambda expression similar to annotating a corresponding anonymous class?


Example:

Annotation:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE_USE)
public @interface MyTypeAnnotation {
    public String value();
}

Working annotation of anonymous class:

Consumer<String> consumer = new @MyTypeAnnotation("Hello ") Consumer<String>() {
    @Override
    public void accept(String str) {
        System.out.println(str);
    }
};

Annotating a lamba expression, currently not working in Java 8:

Consumer<String> myAnnotatedConsumer = @MyTypeAnnotation("Hello") (p -> System.out.println(p));
Holger :

The existence of a Stackoverflow question is not sufficient to indicate that such a feature is planned, not even that someone is ever considering it.

If you look at the list of JEPs, you will see that there is no such JEP, not even in a draft state, suggesting such a feature.

Also, if you look at the current state of Java 9’s LambdaMetafactory, you will see that no change has been made to support passing the meta information that would be necessary to generate a runtime class with recorded annotation data.

There seems to be some desire to add plenty of meta-information to what actually should be a small piece of throw-away code, but I doubt that the language designer will follow it. Lambda expressions are meant to define a function which encapsulates behavior, not an alternative way to describe an anonymous class. The long term evolution will rather lead to lambda expression implementations which are even less of an ordinary class.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=430477&siteId=1