一、通过定义的注解标记指定类的属性,再反编译获取标记属性,进行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;
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Copy {
}
2、需要copy的对象
import com.hyl.light.core.copy.annotation.Copy;
import lombok.Data;
@Data
public class DogBo {
@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;
public class CopyService {
public <T> 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)
二、可以使用自定义的注解给变量、方法、类,打上标记,这对标记做特殊处理。