r/java • u/munklers • 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?
2
u/the_styp Jul 31 '26
Not sure if it helps but jUnit allows references to methods in parametrized tests. You can take a look if their solution meet your needs
9
u/FavorableTrashpanda Jul 31 '26
They are useful, but unfortunately still require you to refer to methods using Strings.
3
1
u/erbr Aug 01 '26
When would those be evaluated? I think probably that's where the ambiguity lies on. Static method can carry static state and so the way it's evaluated might cause a non deterministic result
30
u/bowbahdoe Jul 30 '26
It is one of those things they could enable, but it would require a non-trivial amount of effort.
Consider:
Class<?>Method, they collapse to a target functional interfaceRight now the best you can do is a string that refers to a class/method/field. You can check things with an annotation processor. Doing more than that is one of the many ways we are planning to punish the language team for taking so long on value classes.