微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

原文地址:https://www.jb51.cc/java/121672.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐