今天沈宝问我一个将bean转成map的方法,一下子懵逼了。。。虽然不知道这样转想干啥,但是总感觉牛牛的样子。。。赶紧翻了下apache的common包,果然beantuils有这个功能,可以使用describe的方法
缺点和深浅复制一样,不能递归。直接上代码。
另外有个好的地方就是desciable转成map的时候会多一个class的属性,可以直接获取到当前bean的类
public class BeanTest extends BaseTest {
@Test
public void test() throws SQLException, IOException {
Abean abean=new Abean();
Abeans abeans=new Abeans();
//apache-common:beanuitls--简单类型
//testB:testemptyB
//class:class com.alibaba.dt.op.onedata.BeanTest$Abean
//testA:testemptyA
try {
Map beanMap=BeanUtils.describe(abean);
for(Object key:beanMap.keySet()){
System.out.println(key+":"+beanMap.get(key));
}
} catch (Exception e) {
e.printStackTrace();
}
//apache-common:beanuitls--复杂类型
//abeanList:com.alibaba.dt.op.onedata.BeanTest$Abean@4b2c5e02
//testC:testEmptyC
//class:class com.alibaba.dt.op.onedata.BeanTest$Abeans
try {
Map beanMap=BeanUtils.describe(abeans);
for(Object key:beanMap.keySet()){
System.out.println(key+":"+beanMap.get(key));
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("love u!");
}
public class Abean{
String testA;
String testB;
public Abean(String testA, String testB) {
this.testA = testA;
this.testB = testB;
}
public Abean(){
this.testA="testemptyA";
this.testB="testemptyB";
}
public String getTestA() {
return testA;
}
public void setTestA(String testA) {
this.testA = testA;
}
public String getTestB() {
return testB;
}
public void setTestB(String testB) {
this.testB = testB;
}
}
public class Abeans{
List<Abean> abeanList;
String testC;
public Abeans() {
this.testC="testEmptyC";
List<Abean> abeanList=new ArrayList<Abean>();
for(int i=0;i<3;i++){
Abean abean=new Abean("testA"+i,"testB"+i);
abeanList.add(abean);
}
this.abeanList = abeanList;
}
public List<Abean> getAbeanList() {
return abeanList;
}
public void setAbeanList(List<Abean> abeanList) {
this.abeanList = abeanList;
}
public String getTestC() {
return testC;
}
public void setTestC(String testC) {
this.testC = testC;
}
}