通过java自定义注解与反射机制实现记录实体类属性值变化

通过java自定义注解与反射机制实现记录实体类属性值变化

1.为什么要写这篇文章

今天要做到如何把两个实体类的属性进行封装,以便来判断日志操作。从什么做到什么。

2.自定义注解

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MyTab {
	public String name() default "";
	Integer value() default 0;
}

解析:
@Target :标签作用域标签,可用于方法或者属性上,此定义的是方法上
具体可以根据ElementType的属性定义。
@Retention : 这是用于定义在什么阶段进行标签作用,也是看RetentionPolicy的属性定义
@Documented : 用于生成文档log

3.反射获取属性值

反射利用对象的getClass()方法,再利用getDeclaredFields()获得字段名,值得注意的是,因为获取属性值时,只能获取非private的字段,所以要通过Field的setAccessible设置为true,否则会报错。具体代码如下

public class test {
    public static void main(String[] args) throws IllegalAccessException {
        Student student1 = new Student();
        student1.setName("ab");
        student1.setAgo(14);
        student1.setDate(new Date());
        student1.setShcool("上海");

        Student student2 = new Student();
        student2.setName("aa");
        student2.setAgo(15);
        student2.setDate(new Date());
        student2.setShcool("上海");

        test(student1,student2);
    }
    static void test(Student student1,Student student2) throws IllegalAccessException {
        Field[] declaredFields = student1.getClass().getDeclaredFields();
        Map<String,String> map = new HashMap<>();
        for (Field f : declaredFields) {
            f.setAccessible(true);
            Object o = f.get(student1);
            System.out.println(f.getName()+"   "+o.toString());
            map.put(f.getName(),o.toString());
        }
        Map<String,Object> maps = new HashMap<>();
        Field[] declaredField = student2.getClass().getDeclaredFields();
        for(Field f : declaredField) {
            f.setAccessible(true);
            Object o = f.get(student2);
            System.out.println(f.getName()+"   "+o.toString());
            maps.put(f.getName(),o);
        }

        Set<String> strings = maps.keySet();
        for(String s:strings) {
            if (!Objects.equals(map.get(s),maps.get(s))){
                System.out.println(map.get(s)+"修改为"+maps.get(s));
            }
        }
    }
}

运行截图
运行截图

3.1 反射获取标签值

反射标签是用来记录当属性只是属性名的时候,没有中文的解释,这是需要通过注解来解析每个字段的名字,例如ago解析为年龄。本次利用自定义注解的含义就是这里。
具体代码后续加入

在这里插入代码片

4.总结

通过反射就可以获得相应属性,而不是直接通过get方法一个一个去比较,一来可以提高开发速度,也为代码提高拓展性。在编程的时候需要考虑代码的复用程度,而不是仅仅为了完成当前任务而写代码。


版权声明:本文为weixin_45229417原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。