Tech Me More

To quench our thirst of sharing knowledge about our day to day experience & solution to techincal problems we face in our projects.

Advertise with us !
Send us an email at diehardtechy@gmail.com

Wednesday, April 19, 2017

How to get all the annotated classes of a package with same attribute value?

One of the most common problem when using annotation is to find the classes based upon the attribute value of an annotation. 


Problem-statement: Find all the classes in com.annot package which have @ExampleAnnot annotation and attribute value of author in @ExampleAnnot is dht.

To achieve this we will need the following jars.

1. javassist-3.12.1.GA.jar  which can be Download  from here.

2. org.reflections.0.9.11.jar which can be Download from here


Add both the jar files in your classpath. 



Example code: 


package annot;

import java.util.Set;

import org.reflections.Reflections;
import org.testng.TestListenerAdapter;

public class Lists extends TestListenerAdapter {
 
 public static void main(String[] args) {
  Reflections reflections = new Reflections("com.annot");
  Set<Class<?>> annotated = reflections.getTypesAnnotatedWith(ExampleAnnot.class);
  
  for(Class<?> c:annotated)
  {
   ExampleAnnot declaredAnnotation = c.getDeclaredAnnotation(ExampleAnnot.class);
   if(declaredAnnotation.author().equals("dht"))
   {
    System.out.println(c.getName());
   }
  }
  
 }

}


The above example first finds all the classes with @ExampleAnnot annotation, then sequentially checks the author attribute from @ExampleAnnot of each class , and if author value is equal to dht, it prints the well qualified name of all those class.
Above example returns all the classes which have author name as dht. 



Happy coding. Let us know if you are stuck somewhere.


 

No comments: