实体类1
class Book {
private String name;
private Integer age;
public Book() {
}
public Book(String name, Integer age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Book{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
}
实体类2
class Animal {
private String name;
private Integer age;
private String color;
public Animal() {
}
public Animal(String name, Integer age, String color) {
this.name = name;
this.age = age;
this.color = color;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
@Override
public String toString() {
return "Animal{" +
"name='" + name + '\'' +
", age=" + age +
", color='" + color + '\'' +
'}';
}
}
转换对象之间属性的方法
public static Boolean hasField(Class t,String fieldName){
Field[] declaredFields = t.getDeclaredFields();
for (Field declaredField : declaredFields) {
if (declaredField.getName().equals(fieldName)){
return true;
}
}
return false;
}
public static <E, T> List<T> convertListToList(List<E> oldList, Class<T> eClass) {
List<T> newList = new ArrayList<>();
try {
if (CollectionUtils.isNotEmpty(oldList)) {
Field[] fields = oldList.get(0).getClass().getDeclaredFields();
for (E source : oldList) {
T target = eClass.newInstance();
for (Field field : fields) {
field.setAccessible(true);
if (hasField(eClass,field.getName())) {
Field f = eClass.getDeclaredField(field.getName());
f.setAccessible(true);
f.set(target,field.get(source));
}
}
newList.add(target);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return newList;
}
public static void main(String[] args) {
List<Book> bookList = new ArrayList<>();
bookList.add(new Book("zhangsan", 23));
List<Animal> animals = convertListToList(bookList, Animal.class);
System.out.println(animals);
}
测试成功
|