场景描述:当两个类的实例:a(A),b(B)中的属性有同名属性,类型也一样。这在Java开发当中是经常遇到的。想要将a的属性值赋值给b中的同名属性。
解决方案1:写好多的if…else判断,且代码扩展性太差;
解决方案2:利用Java的内省机制和反射机制。
Apache BeanUtils做的非常好。要是有兴趣可以去好好看看。
以下是笔者写的一段小例子:
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
public class BeanUtilsDemo {
public static void main(String[] args) {
A src = new A();
src.setField1("Beijing");
src.setField2("Shanghai");
B dec = new B();
copyBeanValue(src, dec);
}
public static void copyBeanValue(Object src, Object dec) {
try {
// 自省机制获取Bean信息
BeanInfo srcBeanInfo = Introspector.getBeanInfo(src.getClass());
BeanInfo decBeanInfo = Introspector.getBeanInfo(dec.getClass());
HashMap<String, Method> map = new HashMap<String, Method>();
// 目标的属性描述
PropertyDescriptor[] descriptorDec = decBeanInfo.getPropertyDescriptors();
for (PropertyDescriptor property : descriptorDec) {
String name = property.getName();
Method method = property.getWriteMethod();
if (method != null) {
map.put(name, method);
}
}
// 数据源的属性描述
PropertyDescriptor[] descriptorSrc = srcBeanInfo.getPropertyDescriptors();
for (PropertyDescriptor property : descriptorSrc) {
String name = property.getName();
Method getMethod = property.getReadMethod();
Method setMethod = map.get(name);
if (getMethod != null && setMethod != null) {
try {
Object value = getMethod.invoke(src);
setMethod.invoke(dec, value);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
System.out.println(dec.toString());
} catch (IntrospectionException e) {
e.printStackTrace();
}
}
}
class A {
public String field1;
public String field2;
public String getField1() {
return field1;
}
public void setField1(String field1) {
this.field1 = field1;
}
public String getField2() {
return field2;
}
public void setField2(String field2) {
this.field2 = field2;
}
@Override
public String toString() {
return getField1() + getField2();
}
}
class B {
public String field1;
public String field2;
public String getField1() {
return field1;
}
public void setField1(String field1) {
this.field1 = field1;
}
public String getField2() {
return field2;
}
public void setField2(String field2) {
this.field2 = field2;
}
@Override
public String toString() {
return getField1() + getField2();
}
}