//将origin属性注入到destination中 public <T> void mergeObject(T origin, T destination) { if (origin == null || destination == null) return; if (!origin.getClass().equals(destination.getClass())) return; Field[] fields = origin.getClass().getDeclaredFields(); for (int i = 0; i < fields.length; i++) { try { fields[i].setAccessible(true); Object value = fields[i].get(origin); if (null != value) { fields[i].set(destination, value); } fields[i].setAccessible(false); } catch (Exception e) { } } }
以上是赋值给同类对象,下面是赋值给非同类的对象的同名属性例子
package test.test; import java.lang.reflect.Field; class Temp{ String a = null; String b = null; String c = null; } class Temp2{ String a = null; } public class Test3 { public static void main(String[] args) throws IllegalArgumentException, IllegalAccessException { // TODO Auto-generated method stub Temp t1 = new Temp(); t1.a ="value a"; Temp t2 = new Temp(); t2.b = "value b"; Temp2 t3 = new Temp2(); Field[] fields = t1.getClass().getDeclaredFields(); Field[] fields2 = t3.getClass().getDeclaredFields(); for(int i=0;i<fields.length;i++) if(fields[i].getName().equals(fields2[0].getName())){ fields2[0].set(t3, fields[i].get(t1)); } System.out.println(t3.a); } }