import org.springframework.beans.BeanUtils;import java.time.LocalDate; import java.util.Optional;/*** @author MyHarpers 2020/5/14 21:59*/ publicclassTest{privatestatic Son convertToSon(Father father){return Optional.ofNullable(father).map(o ->{Son entity =newSon();BeanUtils.copyProperties(father, entity);return entity;}).orElseThrow(IllegalArgumentException::new);}publicstaticvoidmain(String[] args){Father father =newFather();father.setAge(8L);father.setBirthday(LocalDate.now());father.setName("姓名");father.setFather("父亲");System.out.println(father);Son son =convertToSon(father);System.out.println(son);son.setSon("儿子");System.out.println(son);} }
输出的消息
Father [name=姓名, age=8, birthday=2020-05-14, father=父亲] Father [name=姓名, age=8, birthday=2020-05-14, son=null] Father [name=姓名, age=8, birthday=2020-05-14, son=儿子]