0

According to JSR 308 (Java Type Annotations) it is possible to annotate any type using ElementType.TYPE_USE:

import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.*;

import java.lang.annotation.Retention;
import java.lang.annotation.Target;

@Target({ TYPE_USE })
@Retention(RUNTIME)
public @interface MyAnnotation {
  String value();
}

How to get the annotated value from a function at runtime?

import java.util.function.Consumer;

import org.junit.Assert;
import org.junit.Test;

public class TestFunctionAnnotation {
  @Test
  public void test() {
    Consumer<TestFunctionAnnotation> fun = @MyAnnotation("NoJoke") TestFunctionAnnotation::test;
    Assert.assertEquals("NoJoke", fun.getClass().getAnnotatedSuperclass().getAnnotation(MyAnnotation.class)); 
   // expected:<NoJoke> but was:<null>
  }
}
jukzi
  • 984
  • 5
  • 14
  • duplicate: https://stackoverflow.com/questions/22375891/annotating-the-functional-interface-of-a-lambda-expression/32957283 – jukzi Feb 09 '20 at 19:40

1 Answers1

2

Your @MyAnnotation doesn't appear on the class, or the method, but on the use of the type - something that you can't reflect on. Instead, you'd need a hypothetical "reflection" which could examine the code itself, not just the structure of the types.

Instead, you want to either build a compiler plugin which can read that, or add a task listener inside an annotation processor - see https://stackoverflow.com/a/55288602/860630 for some discussion on this. Once you've done that and can read the annotation, you can generate new code which you could then access at runtime, and do whatever it is you are after here.

Colin Alworth
  • 17,801
  • 2
  • 26
  • 39