JavaBeanはMapコレクションで互いに変換し、反射を使用します.

17205 ワード

反射が容易にJavaBeanを完了してMap集合に移行し、MapをJavaBeanに変換
1.一般的なエンティティークラスの作成(JavaBean)
/**
 *   javabean(   )
 * 
 * @author ajie
 *
 */
public class TestEntity {

    //   
    private boolean flag;

    //   
    private String name;

    //   
    private double salary;

    //   
    private char sex;

    //   
    private int age;

    //   
    private Date time;

    public TestEntity() {

    }

    public Date getTime() {
        return time;
    }

    public void setTime(Date time) {
        this.time = time;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public boolean isFlag() {
        return flag;
    }

    public void setFlag(boolean flag) {
        this.flag = flag;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getSalary() {
        return salary;
    }

    public void setSalary(double salary) {
        this.salary = salary;
    }

    public char getSex() {
        return sex;
    }

    public void setSex(char sex) {
        this.sex = sex;
    }

}

基本的なプライベート属性とget、setメソッドを設定し、共通のデータ型を使用します.注意:Booleanタイプはgetメソッドがisなので、変換ヘルプを書くときに判断する必要があります.
2.変換ヘルプクラスの作成
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;


/**
 *       map   javabean(   ) javabean   map
 * 
 * @author ajie
 *
 */
public class CollectionUtils {

    //   log  
    static Logger LOG = Logger.getLogger(CollectionUtils.class);

    /**
     * javabean   map  
     * 
     * @param obj
     *               Javabean
     * @return
     * @throws NoSuchMethodException
     * @throws SecurityException
     * @throws IllegalAccessException
     * @throws IllegalArgumentException
     * @throws InvocationTargetException
     */
    public static Map beanToMap(Object obj) throws NoSuchMethodException, SecurityException, IllegalAccessException,
            IllegalArgumentException, InvocationTargetException {
        //   javabean      
        if (obj == null) {
            return null;
        }

        //   javabaen      
        Field[] fields = obj.getClass().getDeclaredFields();

        //   map  
        Map map = new HashMap<>();

        //     
        for (Field fie : fields) {

            //          ,     
            String firstLetter = fie.getName().substring(0, 1).toUpperCase();

            LOG.debug("           ==》》》" + firstLetter);

            //            class
            Class> paramType = fie.getType();

            LOG.debug("     ==》》" + paramType.getName());

            //           get  
            String getter = "";

            //          Boolean  
            if ("boolean".equals(paramType.getName())) {

                //      boolean   is  
                getter = "is" + firstLetter + fie.getName().substring(1);
            } else {

                //     get  
                getter = "get" + firstLetter + fie.getName().substring(1);

            }

            LOG.debug("     ==》》" + getter);

            //   javabean     
            Method method = obj.getClass().getMethod(getter, new Class[] {});

            LOG.debug("     ==》》" + method.toString());

            //   javabean   ,        
            Object returnObj = method.invoke(obj, new Object[] {});

            //        date   ,     get    
            if ("java.util.Date".equals(paramType.getName())) {

                //           
                returnObj = CollectionUtils.dateToString((Date) returnObj);

            }

            //           
            if (returnObj != null) {
                map.put(fie.getName(), returnObj);
            } else {
                map.put(fie.getName(), "");
            }

            LOG.debug("          ==》》" + returnObj);
        }

        LOG.debug("  map     ==》》" + map);

        return map;
    }

    /**
     *  map     Javabean  
     * 
     * @param map
     *              map  
     * @param obj
     *                   javabean
     * @return
     * @throws NoSuchMethodException
     * @throws SecurityException
     * @throws NumberFormatException
     * @throws IllegalAccessException
     * @throws IllegalArgumentException
     * @throws InvocationTargetException
     */
    public static Object mapToBean(Map map, Object obj) throws NoSuchMethodException, SecurityException,
            NumberFormatException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {

        //   javabean     
        Field[] fields = obj.getClass().getDeclaredFields();

        //     
        for (Field fie : fields) {

            //        key 
            if (map.containsKey(fie.getName())) {

                //     map      key  value 
                String value = map.get(fie.getName()).toString();

                LOG.debug("mapToBean:map    value ==》》" + value);

                //              
                String firstLetter = fie.getName().substring(0, 1).toUpperCase();

                //         
                Class> paramType = fie.getType();

                //     set  
                String setter = "set" + firstLetter + fie.getName().substring(1);

                //     javabean    ,       
                Method method = obj.getClass().getMethod(setter, paramType);

                LOG.debug("mapTobean:  javabean    ==》》" + method.toString());

                //      double  
                if ("double".equals(paramType.getName())) {

                    //     Javabean set  ,         
                    method.invoke(obj, Double.valueOf(value));

                    //    char   
                } else if ("char".equals(paramType.getName())) {

                    method.invoke(obj, CollectionUtils.StringToChar(value));

                    //    Date   
                } else if ("java.util.Date".equals(paramType.getName())) {

                    //         ,    
                    Date date = (value == null || value.length() == 0) ? null : CollectionUtils.StringToDate(value);

                    method.invoke(obj, date);

                    //    String   
                } else if ("java.lang.String".equals(paramType.getName())) {

                    method.invoke(obj, value);

                    //    int   
                } else if ("int".equals(paramType.getName())) {

                    method.invoke(obj, Integer.valueOf(value == null ? "0" : value));

                }
            }
        }

        return obj;
    }

    /**
     *  String   char
     * 
     * @param str
     * @return
     */
    public static char StringToChar(String str) {

        //     String   Char  
        char[] charArray = str.toCharArray();

        //   char  
        char newChar = Character.MIN_VALUE;

        //     char
        for (char cha : charArray) {

            newChar += cha;

        }

        return newChar;
    }

    /**
     *       date,   :yyyy-MM-dd HH:mm:ss
     * 
     * @param str
     * @return
     */
    public static Date StringToDate(String str) {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        Date date = null;

        try {
            date = sdf.parse(str);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return date;
    }

    /**
     * date      ,   :yyyy-MM-dd HH:mm:ss
     * 
     * @param time
     * @return
     */
    public static String dateToString(Date time) {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        return sdf.format(time);
    }

}

ここで変換は基本的に反射を使ってJavabeanのすべての属性を取得します.Field[] fields= Javabean.getClass().getDeclaredFields(); ,
取得した属性に基づいてgetフィールドをカプセル化し、getタイプがbooleanの場合、getをisにシフトし、属性の頭文字を大文字に変換する必要があることを覚えておく必要があります.次に、プロパティのタイプを取得し、次のコードを使用します.Class> paramType = fie.getType();、属性タイプに基づいてgetメソッド文をカプセル化し、Method method = Javabean.getClass().getMethod(getter, new Class[] {});設定されたエンティティクラスのgetメソッドを取得し、Methodメソッドクラスのinvoke()メソッドで実行し、getメソッドの戻り値を取得します.コードは次のとおりです.Object returnObj = method.invoke(obj, new Object[] {});
Javabeanの属性に基づいてgetメソッドを呼び出してMapコレクションの変換を完了し、MapコレクションをJavabeanに変換するのも同様の実行方法であり、getをsetに変換するだけである.これは反射を使ってJavabeanとMapコレクションを互いに変換し、学習中のあなたを助けることができることを望んでいる.もっと良い方法で一緒に議論することができる.
次はソースコードダウンロードアドレスです.mapとJavabeanの相互変換インスタンスのソースコードです.