Java 反射API未返回带注释的类
我试图使用,但发现使用自定义注释很难恢复类Java 反射API未返回带注释的类,java,annotations,Java,Annotations,我试图使用,但发现使用自定义注释很难恢复类 URLClassLoader urlClassLoader = new URLClassLoader(plugins.toArray(new URL[plugins.size()]), null); Reflections reflections = new Reflections(new ConfigurationBuilder() .setUrls(ClasspathHelper.f
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()));
我传入一个目录中的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添加到类加载器中
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));
一切都很好。列注释从何而来?如果它是由您编写的,您可以显示它的代码吗?确保列批注具有运行时保留策略:我已添加了Column.class批注代码。