Java examples for java.lang.annotation:Class Annotation
Call to get an annotation that is expected on the given class, throwing a runtime exception if not found.
/**/* w w w . j a v a 2s . co m*/ * Copyright (C) 2011 Tom Spencer <thegaffer@tpspencer.com> * * This file is part of TAL. * * TAL is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * TAL is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with TAL. If not, see <http://www.gnu.org/licenses/>. * * Note on dates: Year above is the year this code was built. This * project first created in 2008. Code was created between these two * years inclusive. */ //package com.java2s; import java.lang.annotation.Annotation; import java.lang.reflect.Method; public class Main { public static void main(String[] argv) throws Exception { Class annotationType = String.class; Class cls = String.class; System.out.println(getExpectedAnnotation(annotationType, cls)); } /** * Call to get an annotation that is expected on the given * class, throwing a runtime exception if not found. * * @param annotationType The expected annotation * @param cls The Java class to check * @return The annotation * @throws IllegalArgumentException If annotation not found */ public static <T extends Annotation> T getExpectedAnnotation( Class<T> annotationType, Class<?> cls) { T ret = cls.getAnnotation(annotationType); if (ret == null) throw new IllegalArgumentException("Expected annotation [" + annotationType + "] not found on class: " + cls); return ret; } /** * Call to get an annotation that is expected on the given * method, throwing a runtime exception if not found. * * @param annotationType The expected annotation * @param method The method to check * @return The annotation * @throws IllegalArgumentException If annotation not found */ public static <T extends Annotation> T getExpectedAnnotation( Class<T> annotationType, Method method) { T ret = method.getAnnotation(annotationType); if (ret == null) throw new IllegalArgumentException("Expected annotation [" + annotationType + "] not found on method: " + method); return ret; } }