我已经搜索了一段时间,似乎有不同的方法,这里总结一下:
-
反思 https://github.com/ronmamo/reflections如果您不介意添加依赖项,该库非常受欢迎。它看起来像这样:
Reflections reflections = new Reflections("firstdeveloper.examples.reflections");
Set<Class<? extends Pet>> classes = reflections.getSubTypesOf(Pet.class);
-
服务加载器(根据埃里克森的回答)它看起来像这样:
ServiceLoader<Pet> loader = ServiceLoader.load(Pet.class);
for (Pet implClass : loader) {
System.out.println(implClass.getClass().getSimpleName()); // prints Dog, Cat
}
请注意,要使其工作,您需要定义Pet
作为 ServiceProviderInterface (SPI) 并声明其实现。你可以通过创建一个文件来做到这一点resources/META-INF/services
与名字examples.reflections.Pet
并声明所有实现Pet
in it
examples.reflections.Dog
examples.reflections.Cat
-
包级注释。这是一个例子:
Package[] packages = Package.getPackages();
for (Package p : packages) {
MyPackageAnnotation annotation = p.getAnnotation(MyPackageAnnotation.class);
if (annotation != null) {
Class<?>[] implementations = annotation.implementationsOfPet();
for (Class<?> impl : implementations) {
System.out.println(impl.getSimpleName());
}
}
}
和注释定义:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PACKAGE)
public @interface MyPackageAnnotation {
Class<?>[] implementationsOfPet() default {};
}
并且您必须在名为的文件中声明包级注释package-info.java
在那个包裹里面。以下是示例内容:
@MyPackageAnnotation(implementationsOfPet = {Dog.class, Cat.class})
package examples.reflections;
请注意,只有当时 ClassLoader 已知的包才会通过调用来加载Package.getPackages()
.
此外,还有其他基于 URLClassLoader 的方法,这些方法始终仅限于已加载的类,除非您进行基于目录的搜索。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)