• 反射和注解的原理


    一,注解的实现原理

    1,定义注解

    @Target(ElementType.TYPE)
    @Retention(RetentionPolicy.RUNTIME)
    public @interface pro {
        String className();
        String methodName();
    }

    2,注解的原理:生成对应注解的实现类

    public class proImpl implements pro{
    
        public String className() {
            return "注解中className对应的参数";
        }
        public String methodName() {
            return "注解中methodName对应的参数";
        }
    
    }

    二,使用注解的原理

      定义一个Check注解,方法用check注解,检查对应的方法处是否有错,有错就将错误的信息写入对应的bug.txt文档中.

    public class Calcuator {
        int a;
        long b;
        @Check
        public int getA() {
            System.out.println("a");
            return a;
        }
        @Check
        public void setA(int a) {
            System.out.println("a");this.a = a;
            throw new Error();
            
        }
        public long getB() {
            System.out.println("get---b");
            return b;
        }
        public void setB(long b) {
            System.out.println("ser---b");
            this.b = b;
        }
        
        @Check
        public long div() {
            return 1/0;
        }
        
    }
    Calcuator
    public @interface Check {
        
    }
    Check.注解
    package annotation;
    
    import java.io.BufferedWriter;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.lang.reflect.Method;
    
    
    
    public class TestCheck {
        public static void main(String[] args) throws IOException {
            Calcuator calcuator=new Calcuator();
            //获取class对象
        Class<? extends Calcuator> class1=calcuator.getClass();
        
            //获取方法
        Method[] methods=class1.getMethods();
        int total=0;//出现异常的次数
        BufferedWriter bw=new BufferedWriter(new FileWriter("bug.txt"));
        
        for(Method method:methods) {
            if(method.isAnnotationPresent(Check.class)) {
                try {
                    method.invoke(calcuator);
                } catch (Exception e) {
                    // TODO: handle exception
                    total++;
                    System.out.println(method.getName());
                    bw.write(method.getName()+"异常方法的名称-----");
                    bw.newLine();
                    
                }
            }
            
        }
        bw.write("出现的总异常数"+total);
        bw.newLine();
        bw.flush();
        bw.close();
        }
    }
    TestCheck.实现原理

     小结:注解是一种有丰富信息的标签,通过反射获取标签的内容,进一步统一处理不同的信息。

  • 相关阅读:
    C语言的指针移位问题
    makefile、gdb使用记录
    MUSIC算法学习笔记
    时间格式转换
    linux网络编程笔记——UDP
    linux网络编程笔记——TCP
    bash里,echo对换行符的处理
    树莓派使用8188eu无线网卡
    时间都去哪了?——安卓GTD工具
    让sublime text 2更好地支持Python
  • 原文地址:https://www.cnblogs.com/gjx1212/p/14764539.html
Copyright © 2020-2023  润新知