[ACCEPTED]-Java - loading annotated classes-classloader

Accepted answer
Score: 31

First answer: Take a look at this project.

Reflections reflections = new Reflections("org.home.junk");
Set<Class<?>> annotated = reflections.getTypesAnnotatedWith(javax.persistence.Entity.class);

It returns all the classes 3 from org.home.junk annotated with javax.persistence.Entity annotation.

Second Answer: To create 2 new instance of above classes you can do 1 this

for (Class<?> clazz : annotated) {
    final Object newInstance = clazz.newInstance();

Hope this answers everything.

Score: 2

If you have Spring(3rd party, sorry :-)), use 2 the org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider

A code usage example can be found in 1 this SO question

Score: 2

It can be done with techniques that check 11 the filesystem because it is more a classloader 10 issue than a reflection one. Check this: Can you find all classes in a package using reflection?.

If 9 you can check all the class files that exists 8 in a directory, you can easily get the corresponding 7 class using this method

Class<?> klass = Class.forName(className)

To know if a class 6 is annotated or not is a reflection issue. Getting 5 the annotations used in a class is done 4 this way:

Annotation[] annotations = klass.getAnnotations();

Be sure to define your custom annotation 3 with a retention policy type visible at 2 run time.


This article is a good resource 1 for more info on that: http://tutorials.jenkov.com/java-reflection/annotations.html.

Score: 1

It all depends on what kind of requirement 12 you have for annotation.

Like e.g. @EJB : This 11 annotation is designed so that container 10 will identify and do EJB Specific work which 9 requires scanning through files and then 8 finding such classes.

However if your requirement 7 is only to enable specific functionality 6 based on annotation then you can do it using 5 java reflection only

e.g. @NotNull : This annotation 4 is designed in JSR 303 to verify that Annotated 3 element is not null. This functionality 2 can be easily implemented at run time using 1 reflection API

More Related questions