001/* 002 * Licensed to the Apache Software Foundation (ASF) under one 003 * or more contributor license agreements. See the NOTICE file 004 * distributed with this work for additional information 005 * regarding copyright ownership. The ASF licenses this file 006 * to you under the Apache License, Version 2.0 (the 007 * "License"); you may not use this file except in compliance 008 * with the License. You may obtain a copy of the License at 009 * 010 * http://www.apache.org/licenses/LICENSE-2.0 011 * 012 * Unless required by applicable law or agreed to in writing, 013 * software distributed under the License is distributed on an 014 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 015 * KIND, either express or implied. See the License for the 016 * specific language governing permissions and limitations 017 * under the License. 018 * 019 */ 020package org.apache.directory.server.core.annotations; 021 022 023import java.lang.annotation.Annotation; 024import java.lang.reflect.Method; 025 026 027/** 028 * An helper class used to find annotations in methods and classes 029 * 030 * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> 031 */ 032public final class AnnotationUtils 033{ 034 private AnnotationUtils() 035 { 036 } 037 038 039 /** 040 * Get an instance of a class extracted from the annotation found in the method 041 * or the class. We iterate on the stack trace until we find the desired annotation. 042 * 043 * @param clazz The Annotation we want to get an instance for 044 * @return The instance or null if no annotation is found 045 * @throws ClassNotFoundException If we can't find a class 046 */ 047 public static Object getInstance( Class<? extends Annotation> clazz ) throws ClassNotFoundException 048 { 049 Object instance = null; 050 051 // Get the caller by inspecting the stackTrace 052 StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace(); 053 054 // Iterate on the stack trace. 055 for ( int i = stackTrace.length - 1; i >= 0; i-- ) 056 { 057 Class<?> classCaller = null; 058 059 // Get the current class 060 try 061 { 062 classCaller = Class.forName( stackTrace[i].getClassName() ); 063 } 064 catch ( ClassNotFoundException cnfe ) 065 { 066 // Corner case : we just have to go higher in the stack in this case. 067 continue; 068 } 069 070 // Get the current method 071 String methodCaller = stackTrace[i].getMethodName(); 072 073 // Check if we have any annotation associated with the method 074 Method[] methods = classCaller.getMethods(); 075 076 for ( Method method : methods ) 077 { 078 if ( methodCaller.equals( method.getName() ) ) 079 { 080 instance = method.getAnnotation( clazz ); 081 082 if ( instance != null ) 083 { 084 break; 085 } 086 } 087 } 088 089 if ( instance == null ) 090 { 091 instance = classCaller.getAnnotation( clazz ); 092 } 093 094 if ( instance != null ) 095 { 096 break; 097 } 098 } 099 100 return instance; 101 } 102}