首页 / 操作系统 / Linux / Java反射之模拟JavaBean接收表单参数
依旧用代码说话。。这是一个Java Project- package com.jadyer.reflection;
-
- import java.io.FileReader;
- import java.lang.reflect.Method;
- import java.util.Enumeration;
- import java.util.Hashtable;
- import java.util.Properties;
-
- import com.jadyer.model.Student;
-
- /**
- * 模拟JavaBean接收表单参数
- */
- public class ImitateJavaBean {
- private static Hashtable<String, Student> mySession; //模拟Web编程中的session对象
-
- static{
- mySession = new Hashtable<String, Student>();
- mySession.put("stu", new Student());
- }
-
- public static void main(String[] args) throws Exception{
- Properties properties = new Properties();
- FileReader fileReader = new FileReader("props.txt");
- properties.load(fileReader); //导入指定文件中所有属性信息
- fileReader.close(); //关闭打开的文件
-
- Enumeration<?> propertiesNames = properties.propertyNames(); //获取所有的属性名
- while(propertiesNames.hasMoreElements()){
- String name = (String)propertiesNames.nextElement();
- String value = properties.getProperty(name);
- ImitateJavaBean.invokeSetter("stu", name, value); //执行setter方法,为属性赋值
- }
-
- System.out.println(ImitateJavaBean.mySession.get("stu")); //输出stu标记的元素的值,即student对象
- }
-
- /**
- * 调用指定属性的setter方法
- * @param beanName-------mySession中的key,通过它可以获取到对应的JavaBean对象
- * @param propertyName---外部资源文件中的name,通过它构造setter方法
- * @param propertyValue--外部资源文件中的value,通过它指定构造的setter的参数值
- */
- public static void invokeSetter(String beanName, String propertyName, String propertyValue) throws Exception{
- Object obj = mySession.get(beanName);
- Class<?> clazz = obj.getClass();
-
- //动态构造一个setter方法,比如name --> setName
- //propertyName.substring(0,1)可以取出属性名的第一个字母
- //propertyName.substring(1)可以从属性名的第2个字母开始取出所有其它的字母
- String methodName = "set" + propertyName.substring(0,1).toUpperCase() + propertyName.substring(1);
-
- //Method method = clazz.getMethod(methodName, java.lang.String.class) //也可以这样写
- Method method = clazz.getMethod(methodName, new Class[]{java.lang.String.class});
-
- method.invoke(obj, propertyValue);//将propertyValue作为该方法的参数值,然后调用该方法
- }
- }
下面是用到的Student类 - package com.jadyer.model;
-
- public class Student {
- private String name;
- private String password;
-
- public void setName(String name) {
- this.name = name;
- }
- public void setPassword(String password) {
- this.password = password;
- }
-
- @Override
- public String toString() {
- return "Name:" + name + " Password:" + password;
- }
- }
最后是用到的位于Java Project根目录中的属性文件props.txt- name = Admin
- password = Jadyer