Как вы знаете, в Java 11 добавлена возможность использовать var в параметрах лямбды, чтобы вы могли добавить аннотацию, но здесь я попытался получить ее во время выполнения, но поскольку лямбда неполноценного класса с его методом, его там нет.
Следует отметить, что он хорошо работает с анонимным классом.
С анонимным классом - вывод:
[[@test.MyAnnotation()]]
public class Main {
public static void main(String[] args) throws NoSuchMethodException {
Consumer<Integer> consumer = new Consumer<Integer>() {
@Override
public void accept(@MyAnnotation Integer integer) {
System.out.println(integer + 1);
}
};
foo(consumer);
}
public static void foo(Consumer<Integer> consumer) throws NoSuchMethodException {
Method method = consumer.getClass().getMethod("accept", Object.class);
Annotation[][] parameterAnnotations = method.getParameterAnnotations();
System.out.println(Arrays.deepToString(parameterAnnotations));
}
}
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation {
}
С лямбдой - Вывод:
[[]]
public class Main {
public static void main(String[] args) throws NoSuchMethodException {
Consumer<Integer> consumer = (@MyAnnotation var integer) -> System.out.println(integer + 1);
foo(consumer);
}
public static void foo(Consumer<Integer> consumer) throws NoSuchMethodException {
Method method = consumer.getClass().getMethod("accept", Object.class);
Annotation[][] parameterAnnotations = method.getParameterAnnotations();
System.out.println(Arrays.deepToString(parameterAnnotations));
}
}
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation {
}
У вас есть какое-нибудь объяснение?