【问题标题】:Scan the classpath for classes with custom annotation [duplicate]使用自定义注释扫描类的类路径[重复]
【发布时间】:2011-09-06 08:45:06
【问题描述】:

例如,如果我有注释 @MyOwnAnnotation 并且在我的类路径中有这些类,那么我可以使用某种过滤器扫描类路径(例如。仅扫描以 my.own.app.* 开头的包)并获取所有类的列表带注释@MyOwnAnnotation?我使用 guice 作为注入框架,我不使用 Spring。

【问题讨论】:

    标签: java guice


    【解决方案1】:

    是的,请查看 Scannotation 库。

    另外,请参阅documents use of Scannotation 的以下博客文章。

    基本示例:

    URL[] urls = ClasspathUrlFinder.findClassPaths(); // scan java.class.path
    AnnotationDB db = new AnnotationDB();
    db.scanArchives(urls);
    Set<String> entityClasses =
        db.getAnnotationIndex().get(MyOwnAnnotation.class.getName());
    

    您的注释需要具有“运行时”保留,以便它们在运行时在.class 文件中可用。

    【讨论】:

    • 您可能会在这里找到其他更好的选择:stackoverflow.com/questions/259140/… 或者如果您没有挂断类路径扫描,请参阅下面的答案以获得替代和更快的解决方案。
    【解决方案2】:

    你可以试试我的图书馆FastClasspathScanner:

    List<String> classNames = new FastClassPathScanner("my.own.app")
        .scan()
        .getNamesOfClassesWithAnnotation(MyOwnAnnotation.class);
    

    【讨论】:

      【解决方案3】:

      我实际上会推荐另一种方法,比所有其他方法都好(因为它们都使用类路径扫描,这很慢)。它被称为 ClassIndex 并且它 INDEXES 注释类:

      https://github.com/atteo/classindex

      【讨论】:

        【解决方案4】:

        你可以试试corn-cps

        例子:

        List<Class<?>> classes = CPScanner.scanClasses(new PackageNameFilter("net.sf.corn.cps.*"),new ClassFilter().appendAnnotation(SampleAnnotation.class));
        

        将下面的依赖项放在你的 pom.xml 中

        <dependency>
            <groupId>net.sf.corn</groupId>
            <artifactId>corn-cps</artifactId>
            <version>1.0.1</version>
        </dependency>
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-10-19
          • 2014-05-28
          • 1970-01-01
          • 1970-01-01
          • 2021-08-10
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多