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

二次信任 提交于 2020-05-10 04:27:07

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!