【发布时间】:2020-02-06 15:22:01
【问题描述】:
根据 JSR 308(Java 类型注释),可以使用 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();
}
如何在运行时从函数中获取注解值?
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>
}
}
【问题讨论】:
标签: java reflection annotation-processing functional-interface