|
在写代码时,有时我们需要写类似的代码,把一个对象的各个属性赋值,或着用另一个和它有着很多成员变量相同的对象赋值,如果这个对象的属性比较多,可以用这个方法省点力气,如果属性较少,还是老老实实的写吧,就不用费这个事了。这个类可以写出类似如下辅助性代码。
obj1.setBirthday()
obj1.setCid()
obj1.setEmail()
obj1.setLogid()
obj1.setLoginemail()
obj1.setLoginmobile()
obj1.setLoginname()
obj1.setLogtime()
obj1.setMid()
obj1.setMobile()
obj1.setName()
obj1.setNickname()
obj1.setOptime()
obj1.setOptype()
obj1.setOpuser()
obj1.setPasswd()
obj1.setRegtime()
obj1.setSex()
obj1.setStatus()
或着类似如下的代码,然后替换掉obj1,obj2就可以了
obj1.setBirthday(obj2.getBirthday())
obj1.setCid(obj2.getCid())
obj1.setEmail(obj2.getEmail())
obj1.setLogid()
obj1.setLoginemail(obj2.getLoginemail())
obj1.setLoginmobile(obj2.getLoginmobile())
obj1.setLoginname(obj2.getLoginname())
obj1.setLogtime()
obj1.setMid(obj2.getMid())
obj1.setMobile(obj2.getMobile())
obj1.setName()
obj1.setNickname(obj2.getNickname())
obj1.setOptime()
obj1.setOptype()
obj1.setOpuser()
obj1.setPasswd(obj2.getPasswd())
obj1.setRegtime(obj2.getRegtime())
obj1.setSex(obj2.getSex())
obj1.setStatus(obj2.getStatus())
这个类的代码如下:,根据需要自行修改。
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import org.apache.commons.beanutils.PropertyUtils;
public class ApacheCommon {
public static void main(String[] args) {
try {
MemberBaseLog obj1 = new MemberBaseLog();
// MemberBase obj2 = new MemberBase();//用另一个对象的时候
MemberBase obj2 = null;// 只用一个对象的时候
PropertyDescriptor origDescriptors[] = PropertyUtils.getPropertyDescriptors(obj1);
for (int i = 0; i < origDescriptors.length; i++) {
String name = origDescriptors.getName();
if ("class".equals(name)) {
continue;
}
Method method = PropertyUtils.getWriteMethod(origDescriptors);
Method method1 = PropertyUtils.getReadMethod(origDescriptors);
if (obj2 != null) {
if (PropertyUtils.isReadable(obj2, name)) {
System.out.println("obj1." + method.getName() + "(" + "obj2." + method1.getName() + "()" + ")");
} else {
System.out.println("obj1." + method.getName() + "()");
}
} else {
System.out.println("obj1." + method.getName() + "()");
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
} |
|
|
|
|
|
|