展开全部
很多情况需要将取得的POJO对象转换成其他表现形式,如Key-Value的Map形式,用于数据展现.本文介绍如何e5a48de588b662616964757a686964616f31333337376262将取得的POJO对象实例后如何转换成Map对象.代码如下
1、类分析器代码,主要是分析类的构造取得类定义的属性和get/set方法
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.hibernate.PropertyNotFoundException;
import org.hibernate.property.BasicPropertyAccessor;
import org.hibernate.property.Getter;
import org.hibernate.property.Setter;
import test.entity.User;
/**
* 分析POJO类抽取类定义的属性和get/set方法
* @author shygiant
*
*/
public class ClassAnalysis {
private Class analysisClass;
private List propertys=new ArrayList();
private List propMeatList=new ArrayList();
private String[] getterNames;
private String[] setterNames;
private Getter[] getters;
private Setter[] setters;
private Class[] propTypes;
private String[] propertyNames;
public ClassAnalysis(Class clazz)
{
this.analysisClass=clazz;
getPropertys(analysisClass);
Iterator itr=propertys.iterator();
BasicPropertyAccessor propertyAccessor=new BasicPropertyAccessor();
while(itr.hasNext())
{
Field field=(Field)itr.next();
ClassPropertyMeta propertyMeta=new ClassPropertyMeta();
try
{
String propertyName=field.getName();
propertyMeta.setProperty(field);
propertyMeta.setGetter(propertyAccessor.getGetter(clazz,propertyName));
propertyMeta.setSetter(propertyAccessor.getSetter(clazz,propertyName));
propertyMeta.setPropType(propertyMeta.getGetter().getReturnType());
propMeatList.add(propertyMeta);
}
catch(PropertyNotFoundException ex)
{
}
}
convertToAry();
}
private void getPropertys(Class clazz)
{
if(clazz!=null&&clazz!=Object.class)
{
Class curClass=clazz.getSuperclass();
getPropertys(curClass);
Field[] fileds=clazz.getDeclaredFields();
for(int i=0;i
{
propertys.add(fileds[i]);
}
}
}
private void convertToAry()
{
int properspan=propMeatList.size();
getters=new Getter[properspan];
getterNames=new String[properspan];
setterNames=new String[properspan];
setters=new Setter[properspan];
propTypes=new Class[properspan];
propertyNames=new String[properspan];
Iterator itr=propMeatList.iterator();
int i=0;
while(itr.hasNext())
{
ClassPropertyMeta propertyMeta=(ClassPropertyMeta)itr.next();
if(propertyMeta!=null)
{
String propertyName=propertyMeta.getProperty().getName();
propertyNames[i]=propertyName;
getters[i]=propertyMeta.getGetter();
setters[i]=propertyMeta.getSetter();
propTypes[i]=getters[i].getReturnType();
getterNames[i]=getters[i].getMethodName();
setterNames[i]=setters[i].getMethodName();
i++;
}
}
}
public class ClassPropertyMeta
{
private Field property;
private Getter getter;
private Setter setter;
private Class propType;
public Field getProperty() {
return property;
}
public void setProperty(Field property) {
this.property = property;
}
public Getter getGetter() {
return getter;
}
public void setGetter(Getter getter) {
this.getter = getter;
}
public Setter getSetter() {
return setter;
}
public void setSetter(Setter setter) {
this.setter = setter;
}
public Class getPropType() {
return propType;
}
public void setPropType(Class propType) {
this.propType = propType;
}
}
public Getter[] getGetters()
{
return getters;
}
public Setter[] getSetters()
{
return setters;
}
public Class[] getPropTypes()
{
return propTypes;
}
public String[] getPropertyNames() {
return propertyNames;
}
public String[] getGetterNames() {
return getterNames;
}
public String[] getSetterNames() {
return setterNames;
}
public static void main(String[] args)
{
User user=new User();
user.setUserId(new Integer("1"));
user.setUserName("abc");
user.setUserPassword("psw");
ClassAnalysis pojoAnalysis=new ClassAnalysis(user.getClass());
Getter[] getters=pojoAnalysis.getGetters();
Class[] propTypes=pojoAnalysis.getPropTypes();
for(int i=0;i
{
System.out.println("getter:="+getters[i].getMethodName());
System.out.println("propTypes:="+propTypes[i].getName());
}
}
public Class getAnalysisClass() {
return analysisClass;
}
}
2、对象分析器代码
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Stack;
import net.sf.cglib.beans.BulkBean;
public class ObjAnalysis {
private Map map;
private String propName="";
private Stack stack;
public ObjAnalysis(Object obj,Class clazz)
{
map=new HashMap();
stack=new Stack();
ClassAnalysis classAnalysis=new ClassAnalysis(clazz);
convertObjToMap(obj,classAnalysis);
}
private void convertObjToMap(Object obj,ClassAnalysis classAnalysis)
{
String[] propertyNames=classAnalysis.getPropertyNames();
String[] getters=classAnalysis.getGetterNames();
String[] setters=classAnalysis.getSetterNames();
Class[] types=classAnalysis.getPropTypes();
BulkBean bulkbean=BulkBean.create(classAnalysis.getAnalysisClass(), getters, setters, types);
Object[] objPropertyValues=bulkbean.getPropertyValues(obj);
for(int i=0;i
{
stack.push(propertyNames[i]);
propName=getPropName(stack);
map.put(propName,objPropertyValues[i]);
if(objPropertyValues[i]!=null)
{
ClassAnalysis clazzAnaly2=new ClassAnalysis(objPropertyValues[i].getClass());
if(clazzAnaly2.getPropertyNames()!=null&&clazzAnaly2.getPropertyNames().length>0)
{
convertObjToMap(objPropertyValues[i],clazzAnaly2);
}
}
stack.pop();
}
}
private String getPropName(Stack stack)
{
String propName="";
Iterator itr=stack.iterator();
int i=0;
while(itr.hasNext())
{
if(i==0)
{
propName=itr.next().toString();
}
else
{
propName+="."+itr.next().toString();
}
i++;
}
return propName;
}
public Map getObjPropertyMap()
{
return map;
}
}
3、辅助类
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import net.sf.cglib.beans.BulkBean;
public class SqlUtil {
public static List convertRsToList(ResultSet rst) throws Exception{
List list = new ArrayList();
Map map = null;
ResultSetMetaData rsmd = null;
try {
rsmd = rst.getMetaData(); // 得到结果集中列类型和属性
int columnCount = rsmd.getColumnCount(); // 得到结果集中包含的列
while (rst.next()) {
map = new HashMap();
for (int i = 0; i < columnCount; i++) {
map.put((String) rsmd.getColumnName(i + 1),
rst.getString(i + 1));
}
list.add(map);
}
}catch(Exception e){
e.printStackTrace();
}
return list;
}
public static List convertObjListToMapList(List objList,Class clazz)
{
List list =new ArrayList();
Iterator itr=objList.iterator();
while(itr.hasNext())
{
Object obj=itr.next();
Map map=convertObjToMap(obj,clazz);
list.add(map);
}
return list;
}
public static Map convertObjToMap(Object obj,Class clazz)
{
Map map=new HashMap();
ObjAnalysis objAnalysis=new ObjAnalysis(obj,clazz);
map=objAnalysis.getObjPropertyMap();
return map;
}
}
4、测试代码
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.hibernate.bytecode.javassist.BulkAccessor;
import org.hibernate.mapping.Component;
import org.hibernate.property.BasicPropertyAccessor;
import org.hibernate.property.Getter;
import org.hibernate.tuple.component.PojoComponentTuplizer;
import net.sf.cglib.beans.BulkBean;
import test.IUser;
import test.UserImpl;
import test.entity.Address;
import test.entity.LinkType;
import test.entity.Role;
import test.entity.User;
public class TestMain {
/**
* @param args
*/
public static void main(String[] args)
{
User user=new User();
user.setUserName("abc");
user.setUserPassword("psw");
Role role=new Role();
role.setRoleId("role1");
role.setRoleName("roleName1");
user.setRole(role);
LinkType linkType=new LinkType();
Address homeAddress=new Address();
homeAddress.setAddressId("addressId1");
homeAddress.setAddressName("addressName1");
Address companyAddress=new Address();
companyAddress.setAddressId("addressId2");
companyAddress.setAddressName("addressName2");
linkType.setHomeAddress(homeAddress);
linkType.setCompanyAddress(companyAddress);
user.setLinkType(linkType);
List userList=new ArrayList();
userList.add(user);
List maplist=SqlUtil.convertObjListToMapList(userList,user.getClass());
for(int i=0;i
{
Map map=(Map)maplist.get(i);
Iterator itr=map.keySet().iterator();
while(itr.hasNext())
{
String key=itr.next().toString();
String value="";
if(map.get(key)!=null)
{
value=map.get(key).toString();
}
System.out.println(key+"="+value);
}
}
}
}
5、POJO实体类
------------------------User.java---------------------------
package test.entity;
// default package
import java.util.Date;
测试结果
linkType.homeAddress=test.entity.Address@29428e
userPassword=psw
linkType.linkTypeId=
linkType=test.entity.LinkType@d0a5d9
linkType.companyAddress=test.entity.Address@388993
linkType.homeAddress.addressId=addressId1
role.roleId=role1
linkType.homeAddress.addressName=addressName1
userId=
userName=abc
role=test.entity.Role@1d04653
linkType.companyAddress.addressId=addressId2
linkType.companyAddress.addressName=addressName2
role.roleName=roleName1
本回答由提问者推荐
已赞过
已踩过<
你对这个回答的评价是?
评论
收起