Reflections API未显示具有注释的接口

时间:2014-07-15 05:10:39

标签: java annotations google-reflections

我正在使用Reflections API来扫描我的java项目并获取具有特定注释的所有类/接口。 然而,它只是返回类而不是接口。

我使用以下内容:

Set<Class<?>> annotated = 
    reflections.getTypesAnnotatedWith(Path.class);

注意:它适用于具有Path注释的类。

因此,Reflections不支持扫描界面吗?或者我必须编写其他代码?

2 个答案:

答案 0 :(得分:0)

你可以尝试一下:

@Documented
@Target(ElementType.METHOD)
@Inherited
@Retention(RetentionPolicy.RUNTIME)
public @interface MethodInfo{
    String author() default "Kuntal";
    String date();
    int revision() default 1;
    String comments();
}


public class AnnotationExample {

    public static void main(String[] args) {
    }

    @Override
    @MethodInfo(author = "Kuntal", comments = "Main method", date = "Nov 17 2012", revision = 1)
    public String toString() {
        return "Overriden toString method";
    }

    @Deprecated
    @MethodInfo(comments = "deprecated method", date = "Nov 17 2012")
    public static void oldMethod() {
        System.out.println("old method, don't use it.");
    }

    @SuppressWarnings({ "unchecked", "deprecation" })
    @MethodInfo(author = "Kuntal", comments = "Main method", date = "Nov 17 2012", revision = 10)
    public static void genericsTest() throws FileNotFoundException {
        List l = new ArrayList();
        l.add("abc");
        oldMethod();
    }

}

然后,您可以使用Reflection来解析类中的java注释。请注意,注释保留策略应该是RUNTIME,否则它的信息将不会在运行时提供,我们将无法从中获取任何数据。

public class AnnotationParsing {

    public static void main(String[] args) {
        try {
            for (Method method : AnnotationParsing.class
                    .getClassLoader()
                    .loadClass(("com.kuntal.annotations.AnnotationExample"))
                    .getMethods()) {
                // checks if MethodInfo annotation is present for the method
                if (method
                        .isAnnotationPresent(com.kuntal.annotations.MethodInfo.class)) {
                    try {
                        // iterates all the annotations available in the method
                        for (Annotation anno : method.getDeclaredAnnotations()) {
                            System.out.println("Annotation in Method '"
                                    + method + "' : " + anno);
                        }
                        MethodInfo methodAnno = method
                                .getAnnotation(MethodInfo.class);
                        if (methodAnno.revision() == 1) {
                            System.out.println("Method with revision no 1 = "
                                    + method);
                        }

                    } catch (Throwable ex) {
                        ex.printStackTrace();
                    }
                }
            }
        } catch (SecurityException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

}

答案 1 :(得分:0)

这应该可行,如here

所示

也许你没有扫描所有相关的网址?在这种情况下,尝试正确构建Reflections对象(使用ClasspathHelper.forClasspath()会扫描所有内容,尽管它可能太宽了......)