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

我有一个注释@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())
    }
}

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

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

解决方法

这是可能的:

>获取类路径中的所有路径.解析System.getProperties().getProperty(“java.class.path”,null)以获取所有路径.
>使用ClassLoader.getResources(path)获取所有资源并检查类:http://snippets.dzone.com/posts/show/4831

相关文章

最近看了一下学习资料,感觉进制转换其实还是挺有意思的,尤...
/*HashSet 基本操作 * --set:元素是无序的,存入和取出顺序不...
/*list 基本操作 * * List a=new List(); * 增 * a.add(inde...
/* * 内部类 * */ 1 class OutClass{ 2 //定义外部类的成员变...
集合的操作Iterator、Collection、Set和HashSet关系Iterator...
接口中常量的修饰关键字:public,static,final(常量)函数...