Bal*_*der 53 java lambda annotations java-8
Java 8引入了Lambda表达式和Type Annotations.
使用类型注释,可以定义Java注释,如下所示:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE_USE)
public @interface MyTypeAnnotation {
public String value();
}
Run Code Online (Sandbox Code Playgroud)
然后可以在任何类型引用上使用此注释,例如:
Consumer<String> consumer = new @MyTypeAnnotation("Hello ") Consumer<String>() {
@Override
public void accept(String str) {
System.out.println(str);
}
};
Run Code Online (Sandbox Code Playgroud)
这是一个完整的例子,它使用这个注释来打印"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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
输出将是:
Hello World!
Hello Type Annotations!
Run Code Online (Sandbox Code Playgroud)
在Java 8中,还可以使用lambda表达式替换此示例中的匿名类:
public static void main(String[] args) {
List<String> list = Arrays.asList("World!", "Type Annotations!");
testTypeAnnotation(list, p -> System.out.println(p));
}
Run Code Online (Sandbox Code Playgroud)
但是,由于编译器为lambda表达式推断了Consumer类型参数,因此无法再对已创建的Consumer实例进行注释:
testTypeAnnotation(list, @MyTypeAnnotation("Hello ") (p -> System.out.println(p))); // Illegal!
Run Code Online (Sandbox Code Playgroud)
可以将lambda表达式转换为Consumer,然后注释转换表达式的类型引用:
testTypeAnnotation(list,(@MyTypeAnnotation("Hello ") Consumer<String>) (p -> System.out.println(p))); // Legal!
Run Code Online (Sandbox Code Playgroud)
但这不会产生所需的结果,因为创建的Consumer类不会使用强制转换表达式的注释进行注释.输出:
World!
Type Annotations!
Run Code Online (Sandbox Code Playgroud)
两个问题:
有没有办法注释一个lambda表达式,类似于注释一个相应的匿名类,所以在上面的例子中得到了预期的"Hello World"输出?
在示例中,我在其中强制转换了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);
}
}
Run Code Online (Sandbox Code Playgroud)
现在,在注释匿名类的参数时,也可以生成"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);
}
});
}
Run Code Online (Sandbox Code Playgroud)
但标注的参数并没有 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));
}
Run Code Online (Sandbox Code Playgroud)
有趣的是,当使用lambda表达式时,也无法接收参数的名称(使用javac -parameter进行编译时).我不确定,如果这个行为是预期的,如果还没有实现lambdas的参数注释,或者这应该被认为是编译器的错误.
Bal*_*der 37
在深入了解Java SE 8 Final Specification之后,我能够回答我的问题.
(1)回答我的第一个问题
有没有办法注释一个lambda表达式,类似于注释一个相应的匿名类,所以在上面的例子中得到了预期的"Hello World"输出?
没有.
当注释Class Instance Creation Expression (§15.9)匿名类型时,注释将存储在类文件中,用于扩展接口或匿名类型的扩展类.
对于以下匿名接口注释
Consumer<String> c = new @MyTypeAnnotation("Hello ") Consumer<String>() {
@Override
public void accept(String str) {
System.out.println(str);
}
};
Run Code Online (Sandbox Code Playgroud)
然后可以通过调用以下命令在运行时访问类型注释Class#getAnnotatedInterfaces():
MyTypeAnnotation a = c.getClass().getAnnotatedInterfaces()[0].getAnnotation(MyTypeAnnotation.class);
Run Code Online (Sandbox Code Playgroud)
如果用这样的空体创建一个匿名类:
class MyClass implements Consumer<String>{
@Override
public void accept(String str) {
System.out.println(str);
}
}
Consumer<String> c = new @MyTypeAnnotation("Hello ") MyClass(){/*empty body!*/};
Run Code Online (Sandbox Code Playgroud)
也可以在运行时通过调用来访问类型注释Class#getAnnotatedSuperclass():
MyTypeAnnotation a = c.getClass().getAnnotatedSuperclass().getAnnotation(MyTypeAnnotation.class);
Run Code Online (Sandbox Code Playgroud)
这种类型的注释是没有可能的lambda表达式.
另外,对于像这样的普通类实例创建表达式,这种注释也是不可能的:
Consumer<String> c = new @MyTypeAnnotation("Hello ") MyClass();
Run Code Online (Sandbox Code Playgroud)
在这种情况下,类型注释将存储在方法的method_info结构中,其中表达式发生,而不是作为类型本身(或其任何超类型)的注释.
这种差异很重要,因为Java反射API在运行时无法访问存储在method_info中的注释.使用ASM查看生成的字节代码时,差异如下所示:
在匿名接口实例创建上键入Annotation:
@Java8Example$MyTypeAnnotation(value="Hello ") : CLASS_EXTENDS 0, null
// access flags 0x0
INNERCLASS Java8Example$1
Run Code Online (Sandbox Code Playgroud)
在普通类实例创建上键入注释:
NEW Java8Example$MyClass
@Java8Example$MyTypeAnnotation(value="Hello ") : NEW, null
Run Code Online (Sandbox Code Playgroud)
在第一种情况下,注释与内部类相关联,而在第二种情况下,注释与方法字节代码中的实例创建表达式相关联.
(2)回应@assylias的评论
您也可以尝试(@MyTypeAnnotation("Hello")String s) - > System.out.println(s)尽管我还没有设法访问注释值...
是的,根据Java 8规范,这实际上是可行的.但目前无法通过Java反射API接收lambda表达式的形式参数的类型注释,这很可能与此JDK错误有关:Type Annotations Cleanup.此外,Eclipse编译器尚未在类文件中存储相关的Runtime [In] VisibleTypeAnnotations属性 - 此处可找到相应的错误:Lambda参数名称和注释不会使其成为类文件.
(3)回答我的第二个问题
在示例中,我在其中强制转换了lambda表达式并注释了转换类型:是否有任何方法可以在运行时接收此批注实例,或者这样的批注是否始终隐式限制为RetentionPolicy.SOURCE?
在注释强制转换表达式的类型时,此信息也会存储在类文件的method_info结构中.对于例如方法的代码内的类型注释的其他可能位置也是如此if(c instanceof @MyTypeAnnotation Consumer).目前没有公共Java反射API来访问这些代码注释.但由于它们存储在类文件中,因此至少可以在运行时访问它们 - 例如,通过使用ASM等外部库读取类的字节代码.
实际上,我设法让我的"Hello World"示例使用类似的强制转换表达式
testTypeAnnotation(list,(@MyTypeAnnotation("Hello ") Consumer<String>) (p -> System.out.println(p)));
Run Code Online (Sandbox Code Playgroud)
通过使用ASM解析调用方法字节代码.但是代码非常hacky和低效,并且在生产代码中可能永远不会做这样的事情.无论如何,只是为了完整性,这里是完整的"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;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13917 次 |
| 最近记录: |