jeudi 6 février 2020

How to get java type annotation of functional by reflection

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>
  }
}




Aucun commentaire:

Enregistrer un commentaire