首先 我们建立一个用户输入的页面,有两个字段:UserName和PassWord
<form action="./UserServlet"> userName:<input type="text" name="userName"/><br> passWord:<input type="text" name="passWord"/><br> <input type="submit" value="login"> </form>
|
然后,我们建立字段的Bean类 进行封装 UserBean:
public class UserBean { private String userName; private String passWord; public String getPassWord() { return passWord; } public void setPassWord(String passWord) { this.passWord = passWord; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } }
|
再次建立一个工具类 就是应用到的反射的核心代码 Tools.java
import java.lang.reflect.Field; import java.lang.reflect.Method;
import javax.servlet.http.HttpServletRequest;
public class Tools { public static Object initBean(HttpServletRequest request,Class cls) { Object obj = null; try { obj = cls.newInstance(); Field[] fields = cls.getDeclaredFields(); for (Field field : fields) { String fieldName = field.getName(); Method method = cls.getDeclaredMethod("set"+fieldName.substring(0,1).toUpperCase()+fieldName.substring(1), new Class[]{String.class}); String value = request.getParameter(fieldName); method.invoke(obj, new Object[]{value}); } } catch (Exception e) { // TODO Auto-generated catch block
e.printStackTrace(); } return obj; } public static void main(String[] args) throws Exception { Class cls = Class.forName("com.accp.UserBean");//根据类名来得到一个Class对象
Class c = UserBean.class;//根据类来得到一个Class对象
Object o = cls.newInstance();//通过类得到一个实例对象 UserBean bean = new UserBean();
} }
|
最后 建立页面提交到的Servlet UserServlet:
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { UserBean bean = (UserBean)Tools.initBean(request, UserBean.class); System.out.println(bean.getUserName()+" "+bean.getPassWord()); }
|
这样就实现了 运用反射 动态获取数据的效果
阅读(3110) | 评论(0) | 转发(0) |