14

I would like to pass a method to an annotation. Is something like this possible?

@MyAnnotation(method = MyClass::myMethod)
private String myVariable;
Dan Grahn
  • 9,044
  • 4
  • 37
  • 74
Frudisch
  • 143
  • 1
  • 5

2 Answers2

17

Passing a method isn't an option. Instead, pass the following which should allow you to find the method using reflection.

@MyAnnotation(clazz=String.class, method="contains", params= {CharSequence.class})

@interface MyAnnotation {
   Class<?> clazz();
   String method();
   Class<?>[] params() default {};
}

MyAnnotation annotation = // get the annotation
annotation.clazz().getMethod(annotation.method(), annotation.params());
Dan Grahn
  • 9,044
  • 4
  • 37
  • 74
  • 2
    Note that annotations allow to omit the braces for single elements arrays, so you may write `params=CharSequence.class` in your example use case. To simplify the no-argument case (even further), I’d use `Class>[] params() default {};` in the annotation type declaration, so you can write, e.g. `@MyAnnotation(clazz=String.class, method="isEmpty")`. – Holger Jun 01 '17 at 10:24
  • 1
    Alternatively, in order to avoid the risk of mistyping `"contains"`, `@interface MyAnnotation` can have a field `Class extends Function> value()` if you are willing to have one (potentially nested) class per function and use reflection to instantiate the function. – Johannes Brodwall Mar 11 '19 at 23:17
5

JSL says:

the annotation attributes only can takes: byte, char, double, float, int, long, short, boolean, String, Enum type, Class, Annotation, 1 dimension array type[type.

but a method reference expression must be assigned to a functional interface. so you can't refer a method reference expression at present.

holi-java
  • 29,655
  • 7
  • 72
  • 83