public class ReflectUtil {public static Class reflectClass(String className){try {return Class.forName(className);} catch (ClassNotFoundException e) {e.printStackTrace();}return null;}public static Object getClassInstance(Class clazz, HttpServletRequest request, HttpServletResponse response){try {Object ins = clazz.newInstance();//invoke setHttpServlet of BaseAction to initialize instance of XXXAction invokeMethodWithArgs(clazz.getSuperclass(), ins, "setHttpServlet",new Class[]{HttpServletRequest.class, HttpServletResponse.class}, request, response);setAttributesForInstance(clazz,ins,request,null);return ins;} catch (Exception e) {e.printStackTrace();} return null;}private static void setAttributesForInstance(Class clazz, Object ins,HttpServletRequest request, String prefix) throws Exception {if(prefix!=null&&prefix.indexOf(".")!=-1) return; //不給二級屬性賦值Field[] fields = clazz.getDeclaredFields();for(Field f : fields){f.setAccessible(true);String typeClass = f.getType().getSimpleName();String fname = f.getName();if(prefix!=null) fname = prefix+"."+fname;String paramValue = request.getParameter(fname);try {if("int".equalsIgnoreCase(typeClass)||"integer".equalsIgnoreCase(typeClass)){if(paramValue != null) f.set(ins, Integer.parseInt(paramValue));}else if("float".equalsIgnoreCase(typeClass)){if(paramValue != null) f.set(ins, Float.parseFloat(paramValue));}else if("double".equalsIgnoreCase(typeClass)){if(paramValue != null) f.set(ins, Double.parseDouble(paramValue));}else if("long".equalsIgnoreCase(typeClass)){if(paramValue != null) f.set(ins, Long.parseLong(paramValue));}else if("short".equalsIgnoreCase(typeClass)){if(paramValue != null) f.set(ins, Short.parseShort(paramValue));}else if("boolean".equalsIgnoreCase(typeClass)){if(paramValue != null) f.set(ins, Boolean.parseBoolean(paramValue));}else if("object".equalsIgnoreCase(typeClass)||"string".equalsIgnoreCase(typeClass)){if(paramValue != null) f.set(ins, paramValue);}else{Object fieldIns = f.getType().getConstructor().newInstance();f.set(ins, fieldIns);setAttributesForInstance(f.getType(), fieldIns, request, fname);}} catch (IllegalArgumentException e) {e.printStackTrace();} catch (IllegalAccessException e) {e.printStackTrace();}}}public static Object invokeMethodNoArgs(Class clazz, Object classInstance, String methodName){Object result = null;try {Method method = clazz.getMethod(methodName);method.setAccessible(true);result = method.invoke(classInstance);} catch (Exception e) {e.printStackTrace();}return result;}public static Object invokeMethodWithArgs(Class clazz, Object classInstance, String methodName, Class[] argType, Object...args){Object result = null;try {Method method = clazz.getDeclaredMethod(methodName, argType);Class returnType = method.getReturnType();method.setAccessible(true);result = method.invoke(classInstance, args);} catch (Exception e) {e.printStackTrace();}return result;}}