Java注解与反射

1.自定义注解

// 自定义注解
@Target(value = {ElementType.METHOD, ElementType.TYPE})// 使用范围:方法
@Retention(RetentionPolicy.RUNTIME)// 作用域:运行时有效
@Documented // 可以被抽取到API文档中
@Inherited // 可以被子类继承。
@interface MyAnnotation {
    // 注解的参数:参数类型 + 参数名();
    String name() default "";// 需要输入一个String类型,不输入默认空字符串。
    String value() default "";// 需要输入一个String类型,不输入默认空字符串。
}

@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();
        }
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容