Here you can find the source of getAnnotations(final Class c, final Class
@SuppressWarnings("unchecked") public static <T> List<T> getAnnotations(final Class c, final Class<T> annClass)
//package com.java2s; /**//from w w w. j ava 2 s .c o m * Copyright (C) 2010 Olafur Gauti Gudmundsson * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.util.ArrayList; import java.util.List; public class Main { /** * Returns the (first) instance of the annotation, on the class (or any superclass, or interfaces implemented). */ @SuppressWarnings("unchecked") public static <T> List<T> getAnnotations(final Class c, final Class<T> annClass) { final List<T> found = new ArrayList<T>(); // TODO isn't that actually breaking the contract of @Inherited? if (c.isAnnotationPresent(annClass)) { found.add((T) c.getAnnotation(annClass)); } Class parent = c.getSuperclass(); while ((parent != null) && (parent != Object.class)) { if (parent.isAnnotationPresent(annClass)) { found.add((T) parent.getAnnotation(annClass)); } // ...and interfaces that the superclass implements for (final Class interfaceClass : parent.getInterfaces()) { if (interfaceClass.isAnnotationPresent(annClass)) { found.add((T) interfaceClass.getAnnotation(annClass)); } } parent = parent.getSuperclass(); } // ...and all implemented interfaces for (final Class interfaceClass : c.getInterfaces()) { if (interfaceClass.isAnnotationPresent(annClass)) { found.add((T) interfaceClass.getAnnotation(annClass)); } } // no annotation found, use the defaults return found; } public static <T> T getAnnotation(final Class c, final Class<T> annClass) { final List<T> found = getAnnotations(c, annClass); if (found != null && !found.isEmpty()) { return found.get(0); } else { return null; } } }