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

前端之家收集整理的这篇文章主要介绍了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.f2er.com/java/121672.html

猜你在找的Java相关文章