通过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");