自己写的工具类,但当参数clazz有父类,而request中又能得到父类属性名称和属性值时,就会出问题
请问高手如何解决?package util;import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Enumeration;import javax.servlet.http.HttpServletRequest;public class RequestParamUtil
{
public static Object getPackedObj(HttpServletRequest request, Class clazz)
{
Object obj = null;
try
{
obj = clazz.newInstance();
Enumeration<String> enumn = request.getParameterNames();
while(enumn.hasMoreElements())
{
String attrName = enumn.nextElement();
String attrValue = request.getParameter(attrName);
String methodName = "set" + attrName.substring(0, 1).toUpperCase() + attrName.substring(1);
Field field = clazz.getDeclaredField(attrName);
Method method = clazz.getMethod(methodName, field.getType());
method.invoke(obj, attrValue);
}
}
catch (SecurityException e)
{
e.printStackTrace();
}
catch (IllegalArgumentException e)
{
e.printStackTrace();
}
catch (InstantiationException e)
{
e.printStackTrace();
}
catch (IllegalAccessException e)
{
e.printStackTrace();
}
catch (NoSuchFieldException e)
{
e.printStackTrace();
}
catch (NoSuchMethodException e)
{
e.printStackTrace();
}
catch (InvocationTargetException e)
{
e.printStackTrace();
}
return obj;
}
}
请问高手如何解决?package util;import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Enumeration;import javax.servlet.http.HttpServletRequest;public class RequestParamUtil
{
public static Object getPackedObj(HttpServletRequest request, Class clazz)
{
Object obj = null;
try
{
obj = clazz.newInstance();
Enumeration<String> enumn = request.getParameterNames();
while(enumn.hasMoreElements())
{
String attrName = enumn.nextElement();
String attrValue = request.getParameter(attrName);
String methodName = "set" + attrName.substring(0, 1).toUpperCase() + attrName.substring(1);
Field field = clazz.getDeclaredField(attrName);
Method method = clazz.getMethod(methodName, field.getType());
method.invoke(obj, attrValue);
}
}
catch (SecurityException e)
{
e.printStackTrace();
}
catch (IllegalArgumentException e)
{
e.printStackTrace();
}
catch (InstantiationException e)
{
e.printStackTrace();
}
catch (IllegalAccessException e)
{
e.printStackTrace();
}
catch (NoSuchFieldException e)
{
e.printStackTrace();
}
catch (NoSuchMethodException e)
{
e.printStackTrace();
}
catch (InvocationTargetException e)
{
e.printStackTrace();
}
return obj;
}
}
楼主【elysium_H】截止到2008-06-25 23:18:47的历史汇总数据(不包括此帖):
发帖数:1 发帖分:10
结贴数:0 结贴分:0
未结数:1 未结分:10
结贴率:0.00 % 结分率:0.00 %
如何结贴请参考这里:http://topic.csdn.net/u/20080501/09/ef7ba1b3-6466-49f6-9d92-36fe6d471dd1.html
父类中的属性 或者名称是否public?