獲取Java類中注解的詳細信息


前言:這篇博客主要是為了后續的獲取SpringMVC中的全部請求URL做的准備。

public class AnnotationHelper {

    private static final AnnotationHelper helper = new AnnotationHelper();
    
    protected AnnotationHelper() {
        
    }
    
    public static AnnotationHelper getInstance() {
        return helper;
    }
    
    /**
     * 得到類上面的注解信息
     * @param scannerClass
     * @param allowInjectClass
     * @return
     */
    public Annotation getClassAnnotation(Class<?> scannerClass , Class<? extends Annotation> allowInjectClass) {
        
        if(!scannerClass.isAnnotationPresent(allowInjectClass)) {
            return null;
        }
        
        return scannerClass.getAnnotation(allowInjectClass);
    }
    
    /**
     * 等到方法級別注解的信息
     * @param scannerClass:需要被掃描的class文件
     * @param allowInjectClass:注解的文件
     * @return
     */
    public List<Annotation> getMethodAnnotation(Class<?> scannerClass , Class<? extends Annotation> allowInjectClass) {
        List<Annotation> annotations = new ArrayList<Annotation>();
        
        for(Method method : scannerClass.getDeclaredMethods()) {
            if(!method.isAnnotationPresent(allowInjectClass)) {
                continue;
            }
            
            annotations.add(method.getAnnotation(allowInjectClass));
        }
        
        return annotations;
    }
    
    /**
     * 使用Java反射得到注解的信息
     * @param annotation
     * @param methodName
     * @return
     * @throws NoSuchMethodException
     * @throws SecurityException
     * @throws IllegalAccessException
     * @throws IllegalArgumentException
     * @throws InvocationTargetException
     */
    public Object getAnnotationInfo(Annotation annotation , String methodName) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
        if(annotation == null) {
            return null;
        }
        
        Method method = annotation.getClass().getDeclaredMethod(methodName, null);
        return method.invoke(annotation, null);
    }
}

要判斷是否存在指定的Java注解,只需要調用isAnnotationPresent方法,就能夠實現是否存在制定的注解。那么,方法以及類上的注解判斷,就能夠輕松搞定。那么,接下來,就是要獲取注解的詳細信息。通過調用getAnnotation方法,就能夠獲取得到該注解,然后通過Java的反射,就能夠獲取得到該注解中指定方法的結果值。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM