欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

servlet的应用------request对象和bean实体的反射关系

程序员文章站 2022-05-24 09:14:05
...

servlet的应用------request对象和bean实体的反射关系

public class FormBeanVO{

	public <T> T getFormBean(HttpServletRequest request, Class<T> k) {
		try {
			T o = k.newInstance();
			for(Method m : k.getDeclaredMethods()) {
				String mName = m.getName();
				String requestName = request.getParameter(setLower(mName.substring(3)));
				if(requestName == null || "".equals(requestName)) continue;
				else {
					if(mName.startsWith("set")) {
						if(m.getParameterTypes()[0].equals(int.class) || 
								m.getParameterTypes()[0].equals(Integer.class)) {
							m.invoke(o, Integer.valueOf(requestName));
						} 
						else if(m.getParameterTypes()[0].equals(boolean.class) || 
								m.getParameterTypes()[0].equals(Boolean.class)) {
							m.invoke(o, Boolean.valueOf(requestName));
						}
						else if(m.getParameterTypes()[0].equals(String.class)) {
							m.invoke(o, requestName);
						}
						else if(m.getParameterTypes()[0].equals(float.class) || 
								m.getParameterTypes()[0].equals(Float.class)) {
							m.invoke(o, Float.valueOf(requestName));
						}
						else if(m.getParameterTypes()[0].equals(long.class) || 
								m.getParameterTypes()[0].equals(Long.class)) {
							m.invoke(o, Long.valueOf(requestName));
						}
						else if(m.getParameterTypes()[0].equals(Timestamp.class)) {
							m.invoke(o, Timestamp.valueOf(requestName));
						}
					}
				}
			}
			return o;
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	private String setLower(String s) {
		StringBuilder builder = new StringBuilder(s);
		String first = s.substring(0, 1).toLowerCase();
		builder.setCharAt(0, first.charAt(0));
		return builder.toString();
	}
}