Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/364.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何从谓词引用中获取注释值?_Java_Performance_Java 8_Annotations - Fatal编程技术网

Java 如何从谓词引用中获取注释值?

Java 如何从谓词引用中获取注释值?,java,performance,java-8,annotations,Java,Performance,Java 8,Annotations,这是源代码 @Retention(RetentionPolicy.RUNTIME) public @interface PredicateMeta { String name(); int data(); String operator(); } public class AnnotationTest { public static void main(String[] args) { Predicate p = getPred();

这是源代码

@Retention(RetentionPolicy.RUNTIME)
public @interface PredicateMeta {
    String name();
    int data();
    String operator();
}

public class AnnotationTest {
    public static void main(String[] args) {

        Predicate p = getPred();
        // how to get annotation values of data, name and operator??
    }


    public static Predicate getPred() {
        @PredicateMeta(data = 0, name = "name", operator = "+")
        Predicate p = (o) ->  true;
        return p;
    }
}
如何获取注释的值


另外,在运行时使用注释会比使用封装字段中的值慢吗?

使用lambdas无法做到这一点

如果您尝试获取
p.getClass().getAnnotatedInterfaces()
,您将看到没有注释

这是实现这一目标的唯一途径:

首先,您必须给出注释
@Target(ElementType.TYPE\u USE)

然后使用匿名类:

public static Predicate getPred() {
            return new @PredicateMeta(data = 0, name = "name", operator = "+")Predicate() {
                @Override
                public boolean test(Object o) {
                    return true;
                }
            };
        }
因此,当调用此函数时,可以获取注释及其参数:

p.getClass().getAnnotatedInterfaces()[0].getAnnotation(PredicateMeta.class)
p.getClass().getAnnotatedInterfaces()[0].getAnnotation(PredicateMeta.class)