我有一个注释@MyAnnotation,我可以用它注释任何类型(类)。然后我有一个名为AnnotatedClassRegister的类,我希望它注册所有用@MyAnnotation注释的类,这样我以后就可以访问它们了。如果可能的话,我想在创建AnnotatedClassRegister时自动注册这些类,最重要的是在实例化带注释的类之前。
我有AspectJ和Guice可供我使用。到目前为止,我想出的唯一解决方案是使用Guice将AnnotatedClassRegister的单例实例注入到一个方面,该方面搜索所有用@MyAnnotation注释的类,并在其构造函数中添加注册此类所需的代码。这种解决方案的缺点是,我需要实例化每个带注释的类,以便由AOP添加的代码能够实际运行,因此我不能利用这些类的延迟实例化。
我的解决方案的简化伪代码示例:
// This is the class where annotated types are registered
public class AnnotatedClassRegister {
public void registerClass(Class<?> clz) {
...
}
}
// This is the aspect which adds registration code to constructors of annotated
// classes
public aspect AutomaticRegistrationAspect {
@Inject
AnnotatedClassRegister register;
pointcutWhichPicksConstructorsOfAnnotatedClasses(Object annotatedType) :
execution(/* Pointcut definition */) && args(this)
after(Object annotatedType) :
pointcutWhichPicksConstructorsOfAnnotatedClasses(annotatedType) {
// registering the class of object whose constructor was picked
// by the pointcut
register.registerClass(annotatedType.getClass())
}
}我应该使用什么方法来解决这个问题?有没有什么简单的方法可以通过反射在类路径中获得所有这样的带注释的类,这样我就根本不需要使用AOP了?或任何其他解决方案?
任何想法都非常感谢,谢谢!
发布于 2021-07-29 03:44:32
您可以像这样使用ClassGraph包:
Java:
try (ScanResult scanResult = new ClassGraph().enableAnnotationInfo().scan()) {
for (ClassInfo classInfo = scanResult.getClassesWithAnnotation(classOf[MyAnnotation].getName()) {
System.out.println(String.format("classInfo = %s", classInfo.getName()));
}
}Scala:
Using(new ClassGraph().enableAnnotationInfo.scan) { scanResult =>
for (classInfo <- scanResult.getClassesWithAnnotation(classOf[MyAnnotation].getName).asScala) {
println(s"classInfo = ${classInfo.getName}")
}
}https://stackoverflow.com/questions/5890003
复制相似问题