Java – register all classes annotated with @ myannotation
I have an annotation @ myannotation, which I can use to annotate any type (class) Then I have a class named annotatedclassregister. I hope it can register all classes annotated with @ myannotation so that I can access them later I want to register these classes automatically when creating annotatedclassregister. If possible, the most important thing is before instantiating the annotated class
I have AspectJ and Guice for my use The only solution I have proposed so far is to use Guice to inject a single instance of annotatedclassregister into an aspect, which searches all classes annotated with @ myannotation and adds the code required to register this class in its constructor The disadvantage of this solution is that I need to instantiate each annotated class to actually run the code added by AOP, so I can't take advantage of the delayed instantiation of these classes
Simplified pseudo code example of my solution:
// 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())
}
}
What method should I use to solve this problem? Is there a simple way to get all these annotated classes in the classpath through reflection, so I don't need to use AOP at all? Or any other solution?
Thank you very much for any ideas, thank you!
Solution
This is possible:
>Gets all paths in the classpath Parse system getProperties(). Getproperty ("Java. Class. Path", null) to get all paths. > Use classloader Getresources (path) get all resources and check the class: http://snippets.dzone.com/posts/show/4831
