java 工具类 ---反射字段值封装到对象中

来源:互联网 发布:网络工具套装软件 编辑:程序博客网 时间:2024/06/15 22:18

在javaEE 开发中,经常需要将页面传过来的值封装到类的属性中。

以便传值或者持久化到数据库中。

可以使用这个简单封装类。


package com.letv.uts2.utcServer.util;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import java.lang.reflect.Method;import java.util.HashMap;import java.util.Map;import java.util.Set;/** * Created by IntelliJ IDEA. * User: haoshihai * Date: 13-3-14 * Time: 下午3:09 * To change this template use File | Settings | File Templates. */public class WrapperModel {    private static final Logger log = LoggerFactory.getLogger(WrapperModel.class);    String userName;    String password;    public String getUserName() {        return userName;    }    public void setUserName(String userName) {        this.userName = userName;    }    public String getPassword() {        return password;    }    public void setPassword(String password) {        this.password = password;    }    public  static <T> T doWrapper(Class c, Map<String, Object> map) throws Exception {        T t = (T) c.newInstance();        try {            Set<Map.Entry<String, Object>> set = map.entrySet();            for (Map.Entry<String, Object> entry : map.entrySet()) {                String fileName = entry.getKey();                Object value = entry.getValue();                log.info("fileName={},value={}", new Object[]{fileName, value});                Method get_Method = c.getMethod("get" + getMethodName(fileName));  //获取getMethod方法                Method set_Method = c.getMethod("set" + getMethodName(fileName), get_Method.getReturnType());//获得属性get方法                Class<?> clazz = get_Method.getReturnType();                String type = clazz.getName(); //获取返回值名称                if (type.equals("long"))                    set_Method.invoke(t, Long.valueOf(value.toString()));  //对于类型 long                else if (type.equals("int") || type.equals("java.lang.Integer"))//对于int 类型                    set_Method.invoke(t, Integer.valueOf(value.toString()));                else if ("java.lang.String".equals(type))                    set_Method.invoke(t,value);                else set_Method.invoke(t, c.cast(value));//其他类型调用class.cast方法            }        } catch (Exception e) {            log.equals("property is errorr!" + e.toString());        }        return t;    }    // 把一个字符串的第一个字母大写、效率是最高的、    private static String getMethodName(String fildeName) {        byte[] items = fildeName.getBytes();        items[0] = (byte) ((char) items[0] - 'a' + 'A');        return new String(items);    }    public static void main(String args[]) throws Exception {        Map map = new HashMap();        map.put("userName", "jim");        map.put("password", "tom");        WrapperModel w2 = (WrapperModel) WrapperModel.doWrapper(WrapperModel.class, map);        System.out.print(w2.getPassword()+"----"+w2.getUserName());    }}

直接拷贝代码运行。