问题
I would like to pass a method to an annotation. Is something like this possible?
@MyAnnotation(method = MyClass::myMethod)
private String myVariable;
回答1:
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());
回答2:
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.
来源:https://stackoverflow.com/questions/44291122/how-do-i-pass-a-method-to-an-annotation-using-java-8