BeanUtils Map與Bean轉換
阿新 • • 發佈:2019-01-31
不多說了,直接上程式碼,以下內容實現限制,javaBean必須在一個單獨的檔案中,並且Bean要為public的。【這裡需要依賴apache的commons-beanutils-1.7.0.jar】
轉換類:
Java程式碼- 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類。
Java程式碼- 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;
- }
- }