Suggested Pages

Friday, January 20, 2017

Search Annotation in a Package Example

A simple java class that allows you to load annotation given a package without import external libraries.

AnnotationResolver.java


package it.boomerang.common;

import java.io.File;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

public class AnnotationResolver {

 public static class AnnotationResult {

  private Class<?> clazz;

  private List<Annotation> annotations;

  public AnnotationResult(Class<?> clazz, List<Annotation> annotations) {
   super();
   this.clazz = clazz;
   this.annotations = annotations;
  }

  public Class<?> getClazz() {
   return clazz;
  }

  public List<Annotation> getAnnotation() {
   return annotations;
  }

  @Override
  public String toString() {
   return "AnnotationResult [clazz=" + clazz + ", annotations=" + annotations + "]";
  }
  
  
 }

 public static List<AnnotationResult> findAnnotation(String packageName, Class<? extends Annotation> annotationClazz) {
  List<AnnotationResult> annotationResults = new ArrayList<>();

  if (packageName==null) {
   throw new IllegalArgumentException("packageName cannot be null");
  }
  if (!annotationClazz.isAnnotation()) {
   throw new IllegalArgumentException("class " + annotationClazz + " is not annotation");
  }
  List<Class<?>> classFromPackage;
  try {
   classFromPackage = getClassFromPackage(packageName);
  } catch (ClassNotFoundException | IOException | URISyntaxException e) {
   return annotationResults;
  }

  if (classFromPackage == null) {
   return annotationResults;
  }

  if (classFromPackage != null)
   for (Class<?> c : classFromPackage) {
    List<Annotation> annotations = new ArrayList<>();
    Method[] methods = c.getMethods();
    if (methods != null) {
     for (Method m : methods) {
      Annotation methodAnnotation = m.getAnnotation(annotationClazz);
      if (methodAnnotation != null) {
       annotations.add(methodAnnotation);
      }
     }
    }
    Field[] fields = c.getFields();
    if (fields != null) {
     for (Field f : fields) {
      Annotation fieldAnnotation = f.getAnnotation(annotationClazz);
      if (fieldAnnotation != null) {
       annotations.add(fieldAnnotation);
      }
     }
    }

    Annotation classAnnotation = c.getAnnotation(annotationClazz);
    if (classAnnotation != null) {
     annotations.add(classAnnotation);
    }
    if (annotations != null && !annotations.isEmpty()) {
     AnnotationResult annotationResult = new AnnotationResult(c, annotations);
     annotationResults.add(annotationResult);
    }
   }
  return annotationResults;
 }

 private static List<Class<?>> getClassFromPackage(String packageName) throws IOException, ClassNotFoundException, URISyntaxException {
  ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
  String path = packageName.replace('.', '/');
  Enumeration<URL> resources = classLoader.getResources(path);
  List<File> dirs = new ArrayList<File>();
  while (resources.hasMoreElements()) {
   URL resource = resources.nextElement();
   URI uri = new URI(resource.toString());
   dirs.add(new File(uri.getPath()));
  }
  List<Class<?>> classes = new ArrayList<Class<?>>();
  for (File directory : dirs) {
   classes.addAll(findClasses(directory, packageName));
  }
  return classes;
 }

 private static List<Class<?>> findClasses(File directory, String packageName) throws ClassNotFoundException {
  List<Class<?>> classes = new ArrayList<Class<?>>();
  if (!directory.exists()) {
   return classes;
  }
  File[] files = directory.listFiles();
  for (File file : files) {
   if (file.isDirectory()) {
    classes.addAll(findClasses(file, packageName + "." + file.getName()));
   } else if (file.getName().endsWith(".class")) {
    classes.add(Class.forName(packageName + '.' + file.getName().substring(0, file.getName().length() - 6)));
   }
  }
  return classes;
 }
}

Logger.java

The class Logger in package "it.boomerang.test" having Deprecated annotation used both at method and at class level.

package it.boomerang.test;

@Deprecated
public interface Logger {

 @Deprecated
 public void log(String msg);
}


Test.java


public class Test {

 public static void main(String[] args) {
  List findAnnotation = AnnotationResolver.findAnnotation("it.boomerang.test", Deprecated.class);
  System.out.println(findAnnotation);
 }
}

output


[AnnotationResult [clazz=interface it.boomerang.test.Logger, annotations=[@java.lang.Deprecated(), @java.lang.Deprecated()]]]


No comments :

Post a Comment

Suggested Pages