Java examples for java.lang.annotation:Class Annotation
check Candidate class for annotation
//package com.java2s; import java.lang.annotation.Annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Target; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; public class Main { public static void main(String[] argv) throws Exception { String className = "java2s.com"; Class searchedAnnotation = String.class; System.out.println(checkCandidate(className, searchedAnnotation)); }//from w w w. j av a 2 s .c o m public static <T extends Annotation> Class<?> checkCandidate( String className, Class<T> searchedAnnotation) { try { Class<?> candidateClass = Class.forName(className); Target target = searchedAnnotation.getAnnotation(Target.class); for (ElementType elementType : target.value()) { switch (elementType) { case TYPE: if (candidateClass.getAnnotation(searchedAnnotation) != null) return candidateClass; break; case CONSTRUCTOR: for (Constructor<?> constructor : candidateClass .getConstructors()) if (constructor.getAnnotation(searchedAnnotation) != null) return candidateClass; break; case METHOD: for (Method method : candidateClass.getMethods()) if (method.getAnnotation(searchedAnnotation) != null) return candidateClass; break; case FIELD: for (Field field : candidateClass.getFields()) if (field.getAnnotation(searchedAnnotation) != null) return candidateClass; break; default: break; } } } catch (ClassNotFoundException e) { } catch (NoClassDefFoundError e) { } return null; } }