今天终于想出了个电子把这个问题解决了。记录一下:
package com.sysnet.test;import java.lang.reflect.Field;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;import java.util.HashMap;import java.util.Iterator;import java.util.Map;public class Test { public static void main(String[] args){ TestVO vo=new TestVO(); vo.setAge(2); vo.setName("shenzhw"); vo.setDesc("sdag"); try{ new Test().t(vo); }catch(Exception e){ e.printStackTrace(); } } //要对VO中的数据类型加以判断 public void t(TestVO vo) throws NoSuchMethodException,InvocationTargetException,IllegalAccessException{ Field[] fields=vo.getClass().getDeclaredFields(); Map<String,Object> valueMap=new HashMap<String,Object>(); for(int i=0;i<fields.length;i++){ Field f=fields[i]; String name=f.getName(); String method="get" + name.substring(0, 1).toUpperCase() + name.substring(1); Method getMethod=vo.getClass().getMethod(method, new Class[]{}); Object value=getMethod.invoke(vo, new Object[]{}); if(value!=null){ valueMap.put(name, value); } } StringBuffer sql=new StringBuffer("select * from t"); if(valueMap.size()>0){ sql.append(" where "); } Iterator<String> iter=valueMap.keySet().iterator(); String key=iter.next(); sql.append(key + "=" + valueMap.get(key)); while(iter.hasNext()){ String k=iter.next(); sql.append(" and " + k + "=" + valueMap.get(k)); } System.out.println(sql.toString()); }}