java 封装字段_java 工具类 —反射字段值封装到对象中 | 学步园

在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 doWrapper(Class c, Map map) throws Exception {

T t = (T) c.newInstance();

try {

Set> set = map.entrySet();

for (Map.Entry 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());

}

}

直接拷贝代码运行。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值