首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Java -注册所有使用@MyAnnotation注释的类

Java -注册所有使用@MyAnnotation注释的类
EN

Stack Overflow用户
提问于 2011-05-05 05:18:47
回答 5查看 9.7K关注 0票数 6

我有一个注释@MyAnnotation,我可以用它注释任何类型(类)。然后我有一个名为AnnotatedClassRegister的类,我希望它注册所有用@MyAnnotation注释的类,这样我以后就可以访问它们了。如果可能的话,我想在创建AnnotatedClassRegister时自动注册这些类,最重要的是在实例化带注释的类之前。

我有AspectJ和Guice可供我使用。到目前为止,我想出的唯一解决方案是使用Guice将AnnotatedClassRegister的单例实例注入到一个方面,该方面搜索所有用@MyAnnotation注释的类,并在其构造函数中添加注册此类所需的代码。这种解决方案的缺点是,我需要实例化每个带注释的类,以便由AOP添加的代码能够实际运行,因此我不能利用这些类的延迟实例化。

我的解决方案的简化伪代码示例:

代码语言:javascript
复制
// 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了?或任何其他解决方案?

任何想法都非常感谢,谢谢!

EN

Stack Overflow用户

发布于 2021-07-29 03:44:32

您可以像这样使用ClassGraph包:

Java:

代码语言:javascript
复制
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:

代码语言:javascript
复制
Using(new ClassGraph().enableAnnotationInfo.scan) { scanResult =>
  for (classInfo <- scanResult.getClassesWithAnnotation(classOf[MyAnnotation].getName).asScala) {
    println(s"classInfo = ${classInfo.getName}")
  }
}
票数 0
EN
查看全部 5 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5890003

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档