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

jan*_*ink 6 java reflection aop annotations guice

我有一个注释@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())
    }
}
Run Code Online (Sandbox Code Playgroud)

我应该用什么方法来解决这个问题?有没有简单的方法通过反射在classpath中获取所有这些带注释的类,所以我根本不需要使用AOP?或任何其他解决方案?

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

Pet*_*ego 7

这是可能的:

  1. 获取类路径中的所有路径.解析System.getProperties().getProperty("java.class.path", null)得到所有路径.

  2. 使用ClassLoader.getResources(path)获得的所有资源,并检查类:http://snippets.dzone.com/posts/show/4831