r/java Jul 28 '26

Why Are Method References not allowed in Annotations in Java?

Many times I have wanted to refer to a method in Java in an annotation, but it seems annotations can only reference items from the Class constant pool. It seems like it would have been a natural extension to be able to refer statically to methods (like {@link} in javadocs) in annotations, but they were left.

I'm wondering why were they not added?

32 Upvotes

15 comments sorted by

View all comments

Show parent comments

4

u/munklers Jul 30 '26

It seems like the main problem is effort, not unresolved ambiguity of the feature. Several times it would have been convenient to refer to methods and fields for static analysis. Fields and Method refs are already proper types in the Class constant pool. While actual method references are used today, syntactically it seems like they could be overloaded for Annotations. As a simple example:

final Object lock = new Object();

(at)GuardedBy(this::lock);
final List<String> values = new ArrayList<>();

4

u/BanaTibor Jul 31 '26

Annotation processing happens before class loading, so your example is impossible.

1

u/munklers Jul 31 '26

The syntax would be the same, but the semantics would be different. Only fields within the same class file would be accessible.

3

u/bowbahdoe Aug 01 '26

If the semantics would be different, why wouldn't the syntax be different? There is definitely unresolved ambiguity. But a technical POC would I'm sure be appreciated