利用javabean技术封装对象

来源:互联网 发布:unity模型优化 编辑:程序博客网 时间:2024/06/03 05:03

利用JavaBean技术读取文本内容并封装成对象:

(此方法可以演变为将 request中的参数,ResultSet中的数据,封装成对象)

javabean 规范:http://www.oracle.com/technetwork/java/javase/documentation/spec-136004.html

1 .要封装的对象:

public class User {

    private int id;

    private String name;

    private Integerage;

    public int getId() {

        returnid;

    }

    public void setId(int id) {

        this.id = id;

    }

    public String getName() {

        returnname;

    }

    public void setName(String name) {

        this.name = name;

    }

    public Integer getAge() {

        returnage;

    }

    public void setAge(Integer age) {

        this.age = age;

    }

}

 

2.读取文本的格式(id|name|age三个“属性”值,使用 |分割)

user.txt

1 | Tom | 10

2 |jerry| 11

 

3.创建配置文件 user.property,内容如下(key 为类名 User ,值为 User的属性):

User=id,name,age

 

4.利用Javabeanapi 操纵 User 对象, 并将文本内容封装成对象或对象集合

importjava.beans.PropertyDescriptor;

importjava.beans.PropertyEditor;

importjava.io.BufferedReader;

importjava.io.File;

importjava.io.FileInputStream;

importjava.io.IOException;

importjava.io.InputStream;

importjava.io.InputStreamReader;

importjava.lang.reflect.Method;

importjava.math.BigDecimal;

importjava.math.BigInteger;

importjava.util.ArrayList;

importjava.util.Arrays;

importjava.util.Date;

importjava.util.HashMap;

importjava.util.List;

importjava.util.Map;

importjava.util.Properties;

 

importcn.gov.cbrc.complaint.editors.CharacterEditor;

importcn.gov.cbrc.complaint.editors.CustomBooleanEditor;

importcn.gov.cbrc.complaint.editors.CustomNumberEditor;

importcn.gov.cbrc.complaint.editors.CustomDateEditor;

importcn.gov.cbrc.complaint.editors.CustomStringEditor;

 

public class ObjUtils {

   

    /**属性编辑器*/

    private static Map<Class<?>,PropertyEditor> defaultEditors ;

   

    static{

    defaultEditors=new HashMap<Class<?>, PropertyEditor>();

    defaultEditors.put(String.class,new CustomStringEditor());

    defaultEditors.put(int.class,new CustomNumberEditor(Integer.class,true));

    defaultEditors.put(Integer.class,new CustomNumberEditor(Integer.class,true));

    }  

    /**

     * 读取文件并组装对象

     * @param clazz 要封装的目标对象类型

     * @param propertiesPath存放对象属性名的properties文件

     * @param propKey存放对象属性名的properties文件的键

     * @param dataFilePath数据文件路径

     * @return

     */

    public static <T> List<T>convertDataFileToObj(Class<T> clazz,String propertiesPath ,StringpropKey,String dataFilePath){

        List<List<String>> values=readFileByLines(dataFilePath);

        List<String> propNames=getPropNames(propertiesPath,propKey);

        returnassembleEntity(clazz, propNames,values) ;

    }

   

    /**

     * 组装对象

     * @param clazz要封装的目标对象类型

     * @param propertyNames目标对象的属性名字集合

     * @param values将要赋给对象的属性值

     * @return

     */

    private static <T> List<T>assembleEntity(Class<T> clazz,List<String> propertyNames,List<List<String>> values){

        T entity=null;

        try {

            entity = clazz.newInstance();

        } catch (Exception e1) {

            e1.printStackTrace();

        }

        List<T> entities = new ArrayList<T>();

        for(List<String> rowValues : values){

            for(int i=0;i<rowValues.size();i++){

                PropertyDescriptor pd = null;

                try {

                    pd = new PropertyDescriptor(propertyNames.get(i),clazz);

                    Method m =pd.getWriteMethod();

                    PropertyEditor pe=defaultEditors.get(pd.getPropertyType());

                    pe.setAsText(rowValues.get(i));

                    m.invoke(entity,pe.getValue());

                } catch (Exception e) {

                    e.printStackTrace();

                }

            }

            entities.add(entity);

            try {

                entity=clazz.newInstance();

            } catch (Exception e){

                e.printStackTrace();

            }

    }

       

        return entities;

    }

   

 

    /**

     * 以行为单位读取文件

     */

    public static List<List<String>> readFileByLines(String filePath) {

        File file = new File(filePath);

        FileInputStream fis =null;

        InputStreamReader isr = null;

        BufferedReader reader = null;

        List<List<String>> values=new ArrayList<List<String>>();

        try {

        fis= new FileInputStream(file);

        isr=new InputStreamReader(fis,"utf-8");//指定以UTF-8编码读入

            System.out.println("以行为单位读取文件内容,一次读一整行:");

            reader = new BufferedReader(isr);

            String tempString = null;

            List<String> strs=null;

            // 一次读入一行,直到读入null为文件结束

            while ((tempString = reader.readLine()) !=null) {

                strs=Arrays.asList(tempString.split("\\|"));

                values.add(strs);

            }

            reader.close();

        } catch (IOException e) {

            e.printStackTrace();

        } finally {

            if (reader !=null) {

                try {

                    reader.close();

                } catch (IOException e1) {

                  e1.printStackTrace();

                }

            }

        }

        return values;

    }

   

//读取user.property 文件中所配置的属性名

    public static List<String> getPropNames(StringpropertiesPath,String key){

        Properties pro = new Properties();

        List<String> propNames=null;

        InputStream in=null;

        try {

            in = Thread.currentThread().getContextClassLoader().getResourceAsStream(propertiesPath);

            pro.load(in);

            propNames = Arrays.asList(pro.getProperty(key).split(","));

        } catch (Exception e) {

            e.printStackTrace();

        }finally{

            try {

                in.close();

            } catch (IOException e) {

                e.printStackTrace();

            }

        }

        return propNames;

    }

   

}

 

5.自定义属性编辑器写法:CustomStringEditor 用于将字符串转换成各种数据类型

 

importjava.beans.PropertyEditorSupport;

 

public class CustomStringEditor extends PropertyEditorSupport {

    public void setAsText(String text) throws IllegalArgumentException {

        super.setValue(text);

    }

}

0 0
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 qq炫舞客户端被修改怎么办 win7玩穿越卡顿怎么办 玩dnf就蓝屏怎么办win7 平板玩fgo闪退怎么办 微信总是说空间不足怎么办 激活卡时遇到服务器错误怎么办 悦平台服务器错误是怎么办 手机银行提示登录服务器错误怎么办 qq漂流瓶封了怎么办 我的世界被冻结怎么办 qq里被屏蔽了怎么办 qq领手游礼包账号存在异常怎么办 笔记本电脑太卡怎么办最有效 华为平板电脑忘记开机密码怎么办 平板电脑忘记开机密码怎么办 平板电脑忘了开机密码怎么办 qq文件已被损坏怎么办 斗地主没痘了怎么办 熹妃q传金币不够用怎么办 苹果手机玩王者卡怎么办 苹果6玩王者荣耀卡怎么办 苹果macbook开不了机怎么办 苹果7震动像拖拉机一样怎么办 win10笔记本玩lol卡怎么办 苹果笔记本密码忘了怎么办 苹果笔记本系统密码忘记了怎么办 qq加好友频繁了怎么办 淘宝买食品有问题怎么办 手机的设置图标没有了怎么办 国家创业贷款还不了会怎么办 手机mac显示:不好使.怎么办? 英雄联盟买皮肤重复怎么办 皮肤很油毛孔又粗怎么办 笔记本电脑玩英雄联盟卡怎么办 win10系统更新不动了怎么办 win7任务栏时间没了怎么办 win10桌面图标都没了怎么办 win10软件图标没了怎么办 电脑内存插板没用了怎么办 win10笔记本开不了机怎么办 cad复制东西变卡怎么办