【问题标题】:Annotating the functional interface of a Lambda Expression注释 Lambda 表达式的功能接口
【发布时间】:2014-04-18 00:37:32
【问题描述】:

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. 1234563 p>

这些示例已经使用 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 -parameter 编译时)。不过,我不确定,如果这种行为是有意的,是否尚未实现 lambda 的参数注释,或者这是否应该被视为编译器的错误。

【问题讨论】:

  • 你也可以试试(@MyTypeAnnotation("Hello ") String s) -&gt; System.out.println(s)虽然我还没有设法访问注释值...
  • @assylias 感谢您的意见 - 好主意。我用带注释的参数做了一些测试,并将结果添加到我的问题的更新部分。
  • @assylias 更新:无法接收 lambda 表达式的形式参数的类型注释,如您的示例所示,很可能与 JDK bug 8027181Eclipse bug 430571 有关。

标签: java lambda annotations java-8


【解决方案1】:

在深入了解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);
    }
};

然后可以通过调用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 中,表达式出现在该方法中,而不是作为类型本身(或其任何超类型)的注释。

这个区别很重要,因为存储在 method_info 中的注解不能在运行时被 Java 反射 API 访问。用ASM查看生成的字节码时,区别如下:

在匿名接口实例创建时键入注释:

@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 的评论

你也可以试试 (@MyTypeAnnotation("Hello ") String s) -> System.out.println(s) 虽然我还没有设法访问 注释值...

是的,根据 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)回答我的第二个问题

在示例中,我确实转换了 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)));

通过使用 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;
    }
}

【讨论】:

  • 感谢分享!我可以如此为 lambda 表达式使用更好的反射功能......我真的希望 Oracle 尽快解决这个问题。
【解决方案2】:

一种可能有用的解决方法是定义空接口,扩展 lambda 将要实现的接口,然后强制转换为这个空接口以使用注释。像这样:

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.function.Consumer;

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

    @MyAnnotation("Get this")
    interface AnnotatedConsumer<T> extends Consumer<T>{};

    public static void main( String[] args )
    {
        printMyAnnotationValue( (AnnotatedConsumer<?>)value->{} );
    }

    public static void printMyAnnotationValue( Consumer<?> consumer )
    {
        Class<?> clas = consumer.getClass();
        MyAnnotation annotation = clas.getAnnotation( MyAnnotation.class );
        for( Class<?> infClass : clas.getInterfaces() ){
            annotation = infClass.getAnnotation( MyAnnotation.class );
            System.out.println( "MyAnnotation value: " + annotation.value() );
        }
    }
}

该注释随后可在该类实现的接口上使用,并且如果您想在其他地方使用相同的注释,则可以重用。

【讨论】:

  • 但是这样就破坏了类型注解的用处?每次都声明一个新的带注释的接口,只是使用 lambda 表达式而不是带注释的匿名接口似乎有点矫枉过正;)您能想到您建议的方法的任何实际用例吗?
  • 我自己使用它,我想将 lambda 传递给一个方法,该方法使用注解为传入的对象(lambda)实例化代理接口,但因为我没有 JDK 类的功能接口我无法向它添加注释。与您最初想要的本质不同的是,注释的声明远离它的使用位置,有点像变量。
  • 但是为什么不直接使用带注释的匿名接口而不是 lambda 表达式 - 或者我错过了什么?
  • 更简洁的语法,毕竟这就是 lambda 的原因。
  • 对我来说,在这种情况下,这不是语法简洁的问题,而是可读性的问题,如果我将接口与注释一起声明为远离它的用法,我认为这将受到严重伤害。让我们希望,JLS 将在未来的某个时候处理类型注释的 lambda... 无论如何 - 感谢分享
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-18
  • 2018-09-11
  • 1970-01-01
相关资源
最近更新 更多