繁体   English   中英

反射 API 不返回带注释的类

[英]Reflection API not returning Annotated class

我正在尝试使用Reflections API,但我发现很难使用自定义注释取回类。

我传入一个目录中的 URL 列表; 单步执行代码似乎找到了具有注释的类。

URLClassLoader urlClassLoader = new URLClassLoader(plugins.toArray(new URL[plugins.size()]), null);

            Reflections reflections = new Reflections(new ConfigurationBuilder()
                    .setUrls(ClasspathHelper.forClassLoader(urlClassLoader))
                    .setScanners(
                            new SubTypesScanner(false),
                            new TypeAnnotationsScanner()));

但是我需要包含注释的类的最后一段代码总是返回和空集。 我做错了什么吗?

classes = reflections.getTypesAnnotatedWith(Column.class, true);

这是注释类;

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Column {
    boolean load() default false;
    Class loaderClass();
    Class criteriaClass();
    String indicator();
    String columnName();
}

看来我的失败点实际上是;

return Sets.newHashSet(concat(forNames(annotated, loaders()), forNames(classes, loaders())));

loaders 方法返回 null。 注释和类 Iterables 都已填写。

好的,所以看起来我有点过于简单了...

我传入的子目录需要使用 URLClassLoader 添加到 ClassLoader。

URLClassLoader childURLClassLoader = new URLClassLoader(plugins.toArray(new URL[plugins.size()]), classLoader);

一旦我这样做了,然后修改了 ConfigurationBuilder;

Reflections reflections = new Reflections(new ConfigurationBuilder()
                    .setScanners(new SubTypesScanner(false), new TypeAnnotationsScanner())
                    .setUrls(ClasspathHelper.forClassLoader(childURLClassLoader)).addClassLoader(childURLClassLoader));

一切都好。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM