Java注解與反射

1.自定義注解

// 自定義注解
@Target(value = {ElementType.METHOD, ElementType.TYPE})// 使用范圍:方法
@Retention(RetentionPolicy.RUNTIME)// 作用域:運(yùn)行時(shí)有效
@Documented // 可以被抽取到API文檔中
@Inherited // 可以被子類繼承。
@interface MyAnnotation {
    // 注解的參數(shù):參數(shù)類型 + 參數(shù)名();
    String name() default "";// 需要輸入一個(gè)String類型,不輸入默認(rèn)空字符串。
    String value() default "";// 需要輸入一個(gè)String類型,不輸入默認(rèn)空字符串。
}

@MyAnnotation
public class UserAnnotation {
    @MyAnnotation(name= "name1")
    public static void oldMethod() {
        System.out.println("old method, don't use it.");
    }
    
    @MyAnnotation(name="name2",value="value1")
    public static void genericsTest() throws FileNotFoundException {
        List<String> l = new ArrayList<>();
        l.add("abc");
        oldMethod();
    }
}
public class AnnotationParsing {
    public static void main(String[] args) {
        try {
            Class<?> loadClass = AnnotationParsing.class
                    .getClassLoader()
                    .loadClass("com.gs.UserAnnotation");
            if (loadClass.isAnnotationPresent(MyAnnotation.class)) {
                Annotation[] declaredAnnotations = loadClass.getDeclaredAnnotations();
                for (Annotation annotation : declaredAnnotations) {
                    System.out.println("Annotation in class '" + annotation);
                }
            }
            
            for (Method method : loadClass.getMethods()) {
                // checks if MethodInfo annotation is present for the method
                if (method.isAnnotationPresent(MyAnnotation.class)) {
                    try {
                        // iterates all the annotations available in the method
                        for (Annotation anno : method.getDeclaredAnnotations()) {
                            System.out.println("Annotation in Method '"
                                    + method + "' : " + anno);
                        }
                        MyAnnotation methodAnno = method.getAnnotation(MyAnnotation.class);
                        if (methodAnno.product().equals("001")) {
                            System.out.println("Method with product is 001 = "+ method);
                        }
 
                    } catch (Throwable ex) {
                        ex.printStackTrace();
                    }
                }
            }
        } catch (SecurityException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容