gpt4 book ai didi

java - 注释 Lambda 表达式的函数接口(interface)

转载 作者:行者123 更新时间:2023-12-01 19:56:35 26 4
gpt4 key购买 nike

Java 8 引入了 Lambda ExpressionsType Annotations .

使用类型注释,可以定义如下 Java 注释:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE_USE)
public @interface MyTypeAnnotation {
public String value();
}

然后可以在任何类型引用上使用此注释,例如:

Consumer<String> consumer = new @MyTypeAnnotation("Hello ") Consumer<String>() {
@Override
public void accept(String str) {
System.out.println(str);
}
};

这是一个完整的示例,它使用此注释来打印“Hello World”:

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.AnnotatedType;
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;

public class Java8Example {
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE_USE)
public @interface MyTypeAnnotation {
public String value();
}

public static void main(String[] args) {
List<String> list = Arrays.asList("World!", "Type Annotations!");
testTypeAnnotation(list, new @MyTypeAnnotation("Hello ") Consumer<String>() {
@Override
public void accept(String str) {
System.out.println(str);
}
});
}

public static void testTypeAnnotation(List<String> list, Consumer<String> consumer){
MyTypeAnnotation annotation = null;
for (AnnotatedType t : consumer.getClass().getAnnotatedInterfaces()) {
annotation = t.getAnnotation(MyTypeAnnotation.class);
if (annotation != null) {
break;
}
}
for (String str : list) {
if (annotation != null) {
System.out.print(annotation.value());
}
consumer.accept(str);
}
}
}

输出将是:

Hello World! 
Hello Type Annotations!

在 Java 8 中,还可以用 lambda 表达式替换本例中的匿名类:

public static void main(String[] args) {
List<String> list = Arrays.asList("World!", "Type Annotations!");
testTypeAnnotation(list, p -> System.out.println(p));
}

但是由于编译器为 lambda 表达式推断出 Consumer 类型参数,因此无法再注释创建的 Consumer 实例:

testTypeAnnotation(list, @MyTypeAnnotation("Hello ") (p -> System.out.println(p))); // Illegal!

可以将 lambda 表达式转换为 Consumer,然后注释转换表达式的类型引用:

testTypeAnnotation(list,(@MyTypeAnnotation("Hello ") Consumer<String>) (p -> System.out.println(p))); // Legal!

但这不会产生期望的结果,因为创建的 Consumer 类不会使用强制转换表达式的注释进行注释。输出:

World!
Type Annotations!

两个问题:

  1. 是否有任何方法可以像注释相应的匿名类一样注释 lambda 表达式,以便获得上例中预期的“Hello World”输出?

  2. 在示例中,我确实转换了 lambda 表达式并注释了转换后的类型:是否有任何方法可以在运行时接收此注释实例,或者此类注释是否始终隐式限制为 RetentionPolicy.SOURCE?

这些示例已使用 javac 和 Eclipse 编译器进行了测试。

更新

我尝试了@assylias 的建议,改为注释参数,这产生了一个有趣的结果。以下是更新后的测试方法:

public static void testTypeAnnotation(List<String> list, Consumer<String> consumer){
MyTypeAnnotation annotation = null;
for (AnnotatedType t : consumer.getClass().getAnnotatedInterfaces()) {
annotation = t.getAnnotation(MyTypeAnnotation.class);
if (annotation != null) {
break;
}
}
if (annotation == null) {
// search for annotated parameter instead
loop: for (Method method : consumer.getClass().getMethods()) {
for (AnnotatedType t : method.getAnnotatedParameterTypes()) {
annotation = t.getAnnotation(MyTypeAnnotation.class);
if (annotation != null) {
break loop;
}
}
}
}
for (String str : list) {
if (annotation != null) {
System.out.print(annotation.value());
}
consumer.accept(str);
}
}

现在,在注释匿名类的参数时,也可以产生“Hello World”结果:

public static void main(String[] args) {
List<String> list = Arrays.asList("World!", "Type Annotations!");
testTypeAnnotation(list, new Consumer<String>() {
@Override
public void accept(@MyTypeAnnotation("Hello ") String str) {
System.out.println(str);
}
});
}

但是注释参数对于 lambda 表达式不起作用:

public static void main(String[] args) {
List<String> list = Arrays.asList("World!", "Type Annotations!");
testTypeAnnotation(list, (@MyTypeAnnotation("Hello ") String str) -> System.out.println(str));
}

有趣的是,使用 lambda 表达式时,也无法接收参数名称(使用 javac 参数编译时)。但我不确定这种行为是否是有意为之,lambda 的参数注释是否尚未实现,或者这是否应该被视为编译器的错误。

最佳答案

深入研究 Java SE 8 Final Specification 后我可以回答我的问题。

(1) 回答我的第一个问题

Is there any way to annotate a lambda expression similar to annotating a corresponding anonymous class, so one gets the expected "Hello World" output in the example above?

没有。

当注释匿名类型的类实例创建表达式(第 15.9) 时,注释将存储在匿名类型的扩展接口(interface)或扩展类的类文件中。

对于下面的匿名接口(interface)注解

Consumer<String> c = new @MyTypeAnnotation("Hello ") Consumer<String>() {
@Override
public void accept(String str) {
System.out.println(str);
}
};

然后可以通过调用Class#getAnnotatedInterfaces()运行时访问类型注释:

MyTypeAnnotation a = c.getClass().getAnnotatedInterfaces()[0].getAnnotation(MyTypeAnnotation.class);

如果创建一个具有空主体的匿名类,如下所示:

class MyClass implements Consumer<String>{
@Override
public void accept(String str) {
System.out.println(str);
}
}
Consumer<String> c = new @MyTypeAnnotation("Hello ") MyClass(){/*empty body!*/};

类型注释也可以在运行时通过调用Class#getAnnotatedSuperclass()来访问:

MyTypeAnnotation a = c.getClass().getAnnotatedSuperclass().getAnnotation(MyTypeAnnotation.class);

这种类型注释对于 lambda 表达式不可能

顺便说一句,这种注释对于像这样的普通类实例创建表达式也是不可能的:

Consumer<String> c = new @MyTypeAnnotation("Hello ") MyClass();

在这种情况下,类型注释将存储在 method_info structure 中方法的,表达式出现的位置,而不是作为类型本身(或其任何父类(super class)型)的注释。

这种差异很重要,因为 Java 反射 API 在运行时无法访问存储在 method_info 中的注释。当使用 ASM 查看生成的字节码时,差异如下:

在匿名接口(interface)实例创建上键入注释:

@Java8Example$MyTypeAnnotation(value="Hello ") : CLASS_EXTENDS 0, null
// access flags 0x0
INNERCLASS Java8Example$1

普通类实例创建时的类型注释:

NEW Java8Example$MyClass
@Java8Example$MyTypeAnnotation(value="Hello ") : NEW, null

在第一种情况下,注释与内部类相关联,在第二种情况下,注释与方法字节内的实例创建表达式相关联代码。

(2)回复@assylias的评论

You can also try (@MyTypeAnnotation("Hello ") String s) -> System.out.println(s) although I have not managed to access the annotation value...

是的,根据 Java 8 规范,这实际上是可能的。但目前还无法通过Java反射API接收lambda表达式形参的类型注解,这很可能与这个JDK bug有关:Type Annotations Cleanup 。此外,Eclipse 编译器尚未在类文件中存储相关的 Runtime[In]VisibleTypeAnnotations 属性 - 相应的错误可在此处找到:Lambda parameter names and annotations don't make it to class files.

(3)回答我的第二个问题

In the example, where I did cast the lambda expression and annotated the casted type: Is there any way to receive this annotation instance at runtime, or is such an annotation always implicitly restricted to RetentionPolicy.SOURCE?

当注释强制转换表达式的类型时,此信息也会存储在类文件的 method_info 结构中。对于方法代码内类型注释的其他可能位置也是如此,例如if(c instanceof @MyTypeAnnotation Consumer)。目前还没有公共(public)的 Java 反射 API 来访问这些代码注释。但由于它们存储在类文件中,因此至少有可能在运行时访问它们 - 例如通过使用外部库读取类的字节码,如 ASM .

实际上,我设法让我的“Hello World”示例使用像

这样的强制转换表达式
testTypeAnnotation(list,(@MyTypeAnnotation("Hello ") Consumer<String>) (p -> System.out.println(p)));

通过使用ASM解析调用方法字节码。但代码非常老套且效率低下,人们可能永远不应该在生产代码中做这样的事情。不管怎样,为了完整起见,这里是完整的工作“Hello World”示例:

import java.lang.annotation.Annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.AnnotatedType;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;

import org.objectweb.asm.AnnotationVisitor;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.Label;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.TypePath;
import org.objectweb.asm.TypeReference;

public class Java8Example {
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE_USE)
public @interface MyTypeAnnotation {
public String value();
}

public static void main(String[] args) {
List<String> list = Arrays.asList("World!", "Type Annotations!");
testTypeAnnotation(list, new @MyTypeAnnotation("Hello ") Consumer<String>() {
@Override
public void accept(String str) {
System.out.println(str);
}
});
list = Arrays.asList("Type-Cast Annotations!");
testTypeAnnotation(list,(@MyTypeAnnotation("Hello ") Consumer<String>) (p -> System.out.println(p)));
}

public static void testTypeAnnotation(List<String> list, Consumer<String> consumer){
MyTypeAnnotation annotation = null;
for (AnnotatedType t : consumer.getClass().getAnnotatedInterfaces()) {
annotation = t.getAnnotation(MyTypeAnnotation.class);
if (annotation != null) {
break;
}
}
if (annotation == null) {
// search for annotated parameter instead
loop: for (Method method : consumer.getClass().getMethods()) {
for (AnnotatedType t : method.getAnnotatedParameterTypes()) {
annotation = t.getAnnotation(MyTypeAnnotation.class);
if (annotation != null) {
break loop;
}
}
}
}
if (annotation == null) {
annotation = findCastAnnotation();
}
for (String str : list) {
if (annotation != null) {
System.out.print(annotation.value());
}
consumer.accept(str);
}
}

private static MyTypeAnnotation findCastAnnotation() {
// foundException gets thrown, when the cast annotation is found or the search ends.
// The found annotation will then be stored at foundAnnotation[0]
final RuntimeException foundException = new RuntimeException();
MyTypeAnnotation[] foundAnnotation = new MyTypeAnnotation[1];
try {
// (1) find the calling method
StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace();
StackTraceElement previous = null;
for (int i = 0; i < stackTraceElements.length; i++) {
if (stackTraceElements[i].getMethodName().equals("testTypeAnnotation")) {
previous = stackTraceElements[i+1];
}
}
if (previous == null) {
// shouldn't happen
return null;
}
final String callingClassName = previous.getClassName();
final String callingMethodName = previous.getMethodName();
final int callingLineNumber = previous.getLineNumber();
// (2) read and visit the calling class
ClassReader cr = new ClassReader(callingClassName);
cr.accept(new ClassVisitor(Opcodes.ASM5) {
@Override
public MethodVisitor visitMethod(int access, String name,String desc, String signature, String[] exceptions) {
if (name.equals(callingMethodName)) {
// (3) visit the calling method
return new MethodVisitor(Opcodes.ASM5) {
int lineNumber;
String type;
public void visitLineNumber(int line, Label start) {
this.lineNumber = line;
};
public void visitTypeInsn(int opcode, String type) {
if (opcode == Opcodes.CHECKCAST) {
this.type = type;
} else{
this.type = null;
}
};
public AnnotationVisitor visitInsnAnnotation(int typeRef, TypePath typePath, String desc, boolean visible) {
if (lineNumber == callingLineNumber) {
// (4) visit the annotation, if this is the calling line number AND the annotation is
// of type MyTypeAnnotation AND it was a cast expression to "java.util.function.Consumer"
if (desc.endsWith("Java8Example$MyTypeAnnotation;") && this.type != null && this.type.equals("java/util/function/Consumer")) {
TypeReference reference = new TypeReference(typeRef);
if (reference.getSort() == TypeReference.CAST) {
return new AnnotationVisitor(Opcodes.ASM5) {
public void visit(String name, final Object value) {
if (name.equals("value")) {
// Heureka! - we found the Cast Annotation
foundAnnotation[0] = new MyTypeAnnotation() {
@Override
public Class<? extends Annotation> annotationType() {
return MyTypeAnnotation.class;
}
@Override
public String value() {
return value.toString();
}
};
// stop search (Annotation found)
throw foundException;
}
};
};
}
}
} else if (lineNumber > callingLineNumber) {
// stop search (Annotation not found)
throw foundException;
}
return null;
};

};
}
return null;
}
}, 0);
} catch (Exception e) {
if (foundException == e) {
return foundAnnotation[0];
} else{
e.printStackTrace();
}
}
return null;
}
}

关于java - 注释 Lambda 表达式的函数接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59036305/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com