Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I pass a method to an annotation using Java 8? [duplicate]

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

@MyAnnotation(method = MyClass::myMethod)
private String myVariable;
like image 934
Frudisch Avatar asked May 31 '17 17:05

Frudisch


2 Answers

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.

like image 105
holi-java Avatar answered Nov 04 '22 11:11

holi-java


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());
like image 37
Dan Grahn Avatar answered Nov 04 '22 10:11

Dan Grahn