3

Is there a way to check if function passed to a method marked with annotation or no?

Here is a code snippet below for better understanding what I want to get.

public class AnnotationExample {

    static void method(Function f) {
        // how to check here is 'f' annotated with @Example or no?
        System.out.println(f.check(5));
    }

    @Example
    static boolean testWithAnnotation(int k) {
        return k == 5;
    }

    static boolean testWithoutAnnotation(int k) {
        return k != 5;
    }

    public static void main(String[] args) {
        method(AnnotationExample::testWithAnnotation);
        method(AnnotationExample::testWithoutAnnotation);
    }
}

@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@interface Example {
    String value() default "example";
}

@FunctionalInterface
interface Function {
    boolean check(int k);
}
  • My instinct says "no", but I could be wrong. – Slaw Aug 05 '21 at 18:22
  • Does this answer your question? [How can I find out which method a lambda applies to?](https://stackoverflow.com/questions/56187586/how-can-i-find-out-which-method-a-lambda-applies-to) – talex Aug 05 '21 at 18:58
  • That's similar question, but it doesn't contains generalized solution. And my question is about annotations, so that's not a duplicate. I also trying to use something like `method((@Example Function) (a) -> a == 1);` with `ElementType.TYPE_USE` but it still not works. – Vladimir Yarovoy Aug 05 '21 at 21:11
  • It isn't exact, but it explains how to get handle of method. You can get class name and method name from there or maybe even reference to reflection `Method` – talex Aug 06 '21 at 14:48

0 Answers0