不多说了,直接上代码,以下内容实现限制,javaBean必须在一个单独的文件中,并且Bean要为public的。【这里需要依赖apache的commons-beanutils-1.7.0.jar】
转换类:
import java.lang.reflect.InvocationTargetException;
import java.util.Map;
import org.apache.commons.beanutils.BeanUtils;
public class test {
public static void main(String[] args) {
Person person1=new Person();
person1.setName("name1");
person1.setSex("sex1");
Map<String, String> map=null;
try {
map = BeanUtils.describe(person1);
//=============Bean转换成Map=======================//
System.out.println(map.size()+">>>>>>>>>>>");
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Person person=test.map2Bean(map, Person.class);
System.out.println(person.getName());
}
/**
*
*
* Map转换层Bean,使用泛型免去了类型转换的麻烦。
* @param <T>
* @param map
* @param class1
* @return
*/
public static <T> T map2Bean(Map<String, String> map, Class<T> class1) {
T bean = null;
try {
bean = class1.newInstance();
BeanUtils.populate(bean, map);
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
return bean;
}
}
目标转换Bean类。
public class Person {
public Person() {
}
private String name;
private String sex;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
}