您的位置:首页 > 编程语言 > Java开发

Java对象与Map的转换

2010-08-12 17:04 471 查看
首先是将map和要被赋值的Bean传进来

public static void setValue(Map map,Object thisObj)
{
Set set = map.keySet();
Iterator iterator = set.iterator();
while (iterator.hasNext())
{
Object obj = iterator.next();
Object val = map.get(obj);
setMethod(obj, val, thisObj);
}
}


调用设值方法setMethod方法(暂时只支持传入String类型字段的处理)

public static void setMethod(Object method, Object value ,Object thisObj)
{
Class c;
try
{
c = Class.forName(thisObj.getClass().getName());
String met = (String) method;
met = met.trim();
if (!met.substring(0, 1).equals(met.substring(0, 1).toUpperCase()))
{
met = met.substring(0, 1).toUpperCase() + met.substring(1);
}
if (!String.valueOf(method).startsWith("set"))
{
met = "set" + met;
}
Class types[] = new Class[1];
types[0] = Class.forName("java.lang.String");
Method m = c.getMethod(met, types);
m.invoke(thisObj, value);
}
catch (Exception e)
{
// TODO: handle exception
e.printStackTrace();
}
}


以上是直接把map数据传进Bean

下面是把Bean转换成map对象输出

public static Map getValue(Object thisObj)
{
Map map = new HashMap();
Class c;
try
{
c = Class.forName(thisObj.getClass().getName());
Method[] m = c.getMethods();
for (int i = 0; i < m.length; i++)
{
String method = m[i].getName();
if (method.startsWith("get"))
{
try{
Object value = m[i].invoke(thisObj);
if (value != null)
{
String key=method.substring(3);
key=key.substring(0,1).toUpperCase()+key.substring(1);
map.put(method, value);
}
}catch (Exception e) {
// TODO: handle exception
System.out.println("error:"+method);
}
}
}
}
catch (Exception e)
{
// TODO: handle exception
e.printStackTrace();
}
return map;
}


直接返回map,可以转换成json对象返回页面,便于Grid读取。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: