有人问:给你一个类的名字,能否知道里面的所有属性和方法。答案是肯定的。不仅可以知道方法,还可任意的调用里面的方法,这就用到了java的反射机制,名字听起来似乎很深奥似的,其实,很简单。下面我们来进行对任意一个对象的拷贝。
1、 首先建立一个实体Bean ,这里我拿Student 为例,有属性:name 和age .里面有get,set 方法。此处省略。。
2、创建一个类,用来拷贝
package com.copy;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import com.entity.Student;
public class CloneClass {
public static Object Copy(Object obj) throws Exception{
Class cls=obj.getClass(); //获得该obj的Class
Object objCopy=cls.newInstance(); //获得新实例
Field fields[]=cls.getDeclaredFields(); //获得所有属性
for (int i = 0; i < fields.length; i++) {
String fieldName=fields[i].getName(); //获得属性名
//得到get、set 方法名
String getMethodName="get"+fieldName.substring(0, 1).toUpperCase()+fieldName.substring(1);
String setMethodName="set"+fieldName.substring(0, 1).toUpperCase()+fieldName.substring(1);
Method getMethod=cls.getMethod(getMethodName, null);//取得get方法
Object value = getMethod.invoke(obj, null); //取得obj中的值
Method setMethod = cls.getMethod(setMethodName, fields[i].getType());
setMethod.invoke(objCopy, value); //通过set方法设置值
}
return objCopy;
}
//测试对象的拷贝
public static void main(String[] args) throws Exception {
Student stu=(Student)Copy(new Student("小高",19));
System.out.println(stu); // 测试结果:
Student [stuName=小高, stuAge=19]
}
}
//ok,显然,以上的拷贝任何一个对象已经成功了。接下来,看看下面的两行代码。
/* Action action = (Action) Class.forName(className).newInstance();
String result = action.execute(); */
解释Struts流程: 通过反射角度,我们来看看Struts的核心的代码,通过xml配置不同的Action 配置,根据表单提交的地点,找到对应name的Action,然后在通过路径创建不同的实例,通过反射调用要提交方法。再将结果返回,与xml中的result 进行配对,通过filterDispacher转发或者重定向到相应的页面去。