如何将一个参数Class <! - ? - >赋予类<a>

时间:2017-07-20 14:40:39

标签: java

In the following code, I analyze a given package to get all classes annotated with a given Annotation.

I want to load them into a Map with their annotation (and its value).

package com.test

@Named("valueToStock")
public class Main {
    @SneakyThrows
    @SuppressWarnings("unchecked")
    public static  ImmutableMap<Class<? extends Annotation>, Class<?>> find(Class<? extends Annotation> annotation, String packageBase) {
        final ClassLoader loader = Thread.currentThread().getContextClassLoader();

        return ClassPath.from(loader).getTopLevelClassesRecursive(packageBase).stream()
                .filter(x -> x.load().getAnnotation(annotation) != null)
                .collect(Collectors.collectingAndThen(Collectors
                        .toMap(x -> x.load().getAnnotation(annotation), x-> x.load()), ImmutableMap::copyOf));
    }

    public static void main(String[] args) {
        find(Named.class, "com.test")
            .forEach((x, y) -> System.out.println(String.format("Class: %s, Annotation: %s", y, x)));
    }
}

My problem: when I try to call x.load().getAnnotation(annotation);

image

我尝试删除extends Annotation,但它不起作用,我找不到其他方法。

修改 也试过

public static <A extends Annotation> ImmutableMap<Class<A>, Class<?>> find(Class<A> annotation, String packageBase) {
    final ClassLoader loader = Thread.currentThread().getContextClassLoader();

    return ClassPath.from(loader).getTopLevelClassesRecursive(packageBase).stream()
            .filter(x -> x.load().getAnnotation(annotation) != null)
            .collect(Collectors.collectingAndThen(Collectors
                    .toMap(x -> x.load().getAnnotation(annotation), x-> x.load()), ImmutableMap::copyOf));
}

仍然有以下错误(编译时相同):

image

修改
在解决了我的问题之后,我发现了另一个错误。注释实例必须是map的值,而不是键;)Pce

1 个答案:

答案 0 :(得分:2)

您需要引入一个命名类型变量。否则,编译器无法知道两个通配符类型应该是相同的类型。

例如:

public static <T extends Annotation>
    ImmutableMap<Class<T>, Class<?>> find(
        Class<T> annotation, String packageBase) {

修改:您还会将注释类型与注释实例混淆。 Class.getAnnotation(Class<A>)返回A,而不是Class<A>

您可能希望返回由注释实例键入的地图(例如ImmutableMap<A, Class<?>>)。如果您确实需要Class<A>个对象作为键,那么您不需要getAnnotation。只需使用x.load().hasAnnotation(annotation) ? annotation : null或等效的内容。