Java Reflections获取特定子包的url

标签 java reflection

我们正在构建一个测试框架,并使用反射来扫描包中已使用我们定义的注释进行注释的方法。 一切都按预期进行, 然而, 我们遇到了一些奇怪的事情。

使用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/

相关文章:

快速选择器 : how to construct instance referring to method with parameters?

java - 获取属于某个类的所有对象

c# - Activator.CreateInstance MissingMethodException 异常

Java鼠标监听器

java - 如何获得 float 的小数部分?

java - 将 websocket 通信从客户端重定向到服务器到另一个 websocket 服务器

java - 访问自定义线程方法

C# 在运行时创建构造函数

go - 实现一个通用的参数方法

java - 在 IntelliJ IDEA 中编辑并继续?