我们正在构建一个测试框架,并使用反射来扫描包中已使用我们定义的注释进行注释的方法。 一切都按预期进行, 然而, 我们遇到了一些奇怪的事情。
使用ClasspathHelper
来自org.reflections.util
将返回 Set<URL>
,
但它似乎返回父文件夹的 URL,而不是我们想要扫描的实际包的 URL。
例如,
我们运行ClasspathHelper.forPackage("com.company.project.packageWeWantScanned")
,
我们将得到一个指向包含所有类的文件夹的 URL,而不是指向该特定包的 URL。
例如,在下面的示例文件结构中,
我们得到一个指向classes
的URL而不是packageWeWantScanned
.
我们如何只扫描我们想要的特定包而不是父文件夹中的所有类?
classes
└── com
└── company
└── project
├── packageWeWantScanned
│ ├── SomeClass.class
│ ├── SomeOtherClass.class
│ └── SomeOtherClass.class
└── packageWeDontWantScanned
├── DifferentClass.class
├── DifferentOtherClass.class
└── DifferentSomeOtherClass.class
编辑/更新:Sotirios Delimanolis
的答案是正确的,但只是为了为遇到这个问题的人添加额外的上下文,我们最初使用的是:
Reflections reflection = new Reflections(ClasspathHelper.forPackage("com.company.project.packageWeWantScanned"), new MethodAnnotationsScanner());
这导致我们得到的比我们想要的更多。
最佳答案
这就是ClasspathHelper#forPackage(String, ClassLoader..)
确实
effectively returns urls from classpath with packages starting with [name]
您可能想使用 Reflections#getMethodsAnnotatedWith(Class)
.
Reflections reflections = new Reflections("com.company.project.packageWeWantScanned", new MethodAnnotationsScanner());
System.out.println(reflections.getMethodsAnnotatedWith(SomeAnnotation.class));
关于Java Reflections获取特定子包的url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25898724/