Reputation: 12658
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));
Upvotes: 21
Views: 3273
Reputation: 298233
The existence of a Stack Overflow 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.
Upvotes: 18
Reputation: 120858
it's interesting that they do annotate the inner class that "represents" the lambda expression in InnerClassLambdaMetafactory.spinInnerClass
via :
mv.visitAnnotation("Ljava/lang/invoke/LambdaForm$Hidden;", true)
But that is annotating a class obviously, not a lambda per-se.
Annotating a lambda would require changes to the invokedynamic
and implicitly the LambdaMetafactory
as far as I can see - and what would happen when invokedynamic would not create a class for the lambda, but something else, what would happen to those annotations?
Upvotes: 9
Reputation: 718886
According to the What's new in Oracle JDK 9 page, No. This has not changed in Java 9.
Of course, that is not definitive, but the JLS for Java 9 has not been released yet.
Upvotes: 7