自定义注解 实现指定字段备份

通过定义的注解标记指定类的属性,再反编译获取标记属性,进行copy熟悉

1、自定义注解

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * @author huangyl
 * @version V2.1
 * @since 2.1.0 2019-06-19 14:34
 */
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Copy {
}

2、需要copy的对象

import com.hyl.light.core.copy.annotation.Copy;

import lombok.Data;

/**
 * @author huangyl
 * @version V2.1
 * @since 2.1.0 2019-06-19 14:34
 */
@Data
public class DogBo {

    /**  标记copy属性 */
    @Copy
    private String name;

    private String wow;
}

3、处理类

import java.lang.reflect.Field;
import java.util.Arrays;

import com.hyl.light.core.copy.annotation.Copy;
import com.hyl.light.core.copy.bo.DogBo;

/**
 * @author huangyl
 * @version V2.1
 * @since 2.1.0 2019-06-19 14:41
 */
public class CopyService {

    public  T copyBo(T t) throws Exception {

        //新建结果对象
        T result = (T) t.getClass()
            .newInstance();

        //获取变量
        Field[] fields = t.getClass()
            .getDeclaredFields();

        Arrays.stream(fields)
            //根据注解判断变量
            .filter(field -> field.isAnnotationPresent(Copy.class))
            .peek(field -> {
                field.setAccessible(true);
                try {
                    System.out.println(field.getName() + ":" + field.get(t));
                    //复制
                    field.set(result, field.get(t));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            })
            .forEach(System.out::println);

        return result;
    }

    public static void main(String[] args) throws Exception {
        CopyService copyService = new CopyService();

        DogBo dogBo = new DogBo();
        dogBo.setName("maomao");
        dogBo.setWow("wangwang");

        System.out.println(dogBo);
        DogBo dogBo1 = copyService.copyBo(dogBo);

        System.out.println(dogBo1);

    }

}

4、执行结果

DogBo(name=maomao, wow=wangwang)
name:maomao
private java.lang.String com.hyl.light.core.copy.bo.DogBo.name
DogBo(name=maomao, wow=null)

可以使用自定义的注解给变量、方法、类,打上标记,这对标记做特殊处理。

你可能感兴趣的:(自定义注解 实现指定字段备份)