加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-14 05:42:18 所属栏目:Java 来源:网络整理
导读:我有一个注释@MyAnnotation,我可以使用它注释任何类型(类).然后我有一个名为AnnotatedClassRegister的类,我希望它能注册所有用@MyAnnotation注释的类,以便我以后可以访问它们.我想在创建AnnotatedClassRegister时自动注册这些类,如果可能的话,最重要的是在实
我有一个注释@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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读