当前位置: 首页 > 面试题库 >

注释Lambda表达式的功能接口

太叔英锐
2023-03-14
问题内容

Java
8引入了Lambda表达式和类型注释。

使用类型注释,可以定义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表达式转换为使用者,然后注释转换表达式的类型引用:

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
-parameter编译时)。不过,我不确定是否要执行此行为,是否尚未实现lambda的参数注释,还是应该将其视为编译器的错误。


问题答案:

在深入研究Java SE 8最终规范之后,我可以回答我的问题。

(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结构中,而不是类型本身(或其任何超类型的注释)。

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

在创建匿名接口实例时输入Annotation:

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

在普通的类实例创建时输入Annotation:

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

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

(2)回应@assylias的评论

您也可以尝试(@MyTypeAnnotation(“ H​​ello”)String s)->
System.out.println(s),尽管我尚未设法访问注释值…

是的,根据Java
8规范,这实际上是可能的。但是,目前尚无法通过Java反射API接收lambda表达式的形式参数的类型注释,这很可能与以下JDK错误有关:类型注释清除。此外,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)));

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


 类似资料:
  • Java8同时引入了Lambda表达式和类型注释。 可以将lambda表达式强制转换为使用者,然后注释强制转换表达式的类型引用: 但这不会产生所需的结果,因为创建的使用者类不会用强制转换表达式的批注进行批注。产出: 两个问题: 但是注释参数对lambda表达式不起作用: 有趣的是,当使用lambda表达式时,也不可能接收参数的名称(当使用javac-parameter编译时)。不过,我不确定这种行

  • 用Java 8 lambdas到处乱搞。为什么当我向接口添加另一个方法时,这会给我一个错误: 不使用第二个方法也能正常工作:“public int getID(String name)

  • 而不是像这样使用匿名类 对于java 8,我可以使用lambda表达式: 但是如果我的接口中的方法被注释了呢? 可以注释lambda表达式吗?(具体来说,我想对lambda表达式使用Guava的EventBus.register()方法)

  • 但是如果我的接口中的方法是注释的呢? 有可能注释lambda表达式吗?(具体地说,我想使用Guava的eventbus.register()方法和lambda表达式)

  • 静态编程语言允许注释表达式。然而,尚不清楚这些注释如何有用以及如何使用它们。 假设在下面的示例中,我想检查一下,该字符串包含@MyExpr注释中指定的数字。这能实现吗?如何实现?

  • 问题内容: 我需要使用批注+正则表达式对电子邮件进行验证。我尝试使用以下内容: 但是,当电子邮件字段中的电子邮件地址不正确时,我不知道如何打印错误消息。有任何想法吗? 问题答案: 首先,您应该在注释中添加一个属性。假设您的邮件变量是某个类User的一部分: 然后,您应该定义一个验证器: 然后找到验证错误。