初始反射

来源:互联网 发布:柏拉图交友软件 编辑:程序博客网 时间:2024/06/05 02:13
[java] view plain copy
 print?
  1. import java.lang.reflect.Constructor;  
  2. import java.lang.reflect.Field;  
  3. import java.lang.reflect.Method;  
  4.   
  5. /** 
  6.  * 通过反射机制来复制JavaBean对象 
  7.  * @author WalkingDog 
  8.  * 
  9.  */  
  10.   
  11. public class Reflect {  
  12.           
  13.     public static void main(String[] args) throws Exception {  
  14.         Person person = new Person("walkingdog"20);  
  15.         person.setId(2009324116L);  
  16.         Person personCopy = (Person)new Reflect().copy(person);  
  17.         System.out.println(personCopy.getId() + " " + personCopy.getName() + "  " + personCopy.getAge());  
  18.     }  
  19.       
  20.     public Object copy(Object object) throws Exception{  
  21.           
  22.         //要想使用反射,首先需要获得待处理类或对象所对应的Class对象  
  23.         //下面是获取Class对象的常用的3种方式  
  24.         //获得运行时的类  
  25.         Class<?> classType = object.getClass();  
  26.         //Class<?> classType = Costomer.class;  
  27.         //Class<?> classType = Class.forName("Costomer");  
  28.            
  29.         Constructor<?> constructor = classType.getConstructor(new Class<?>[]{});  
  30.           
  31.         Object objectCopy = constructor.newInstance(new Object[]{});  
  32.           
  33.         //以上两行代码等价于下面一行代码,newInstance()只能通过无参构造方法建立对象。  
  34.         //Object objectCopy = classType.newInstance();  
  35.           
  36.         Field fields[] = classType.getDeclaredFields();  
  37.         for(Field field : fields){  
  38.             String name = field.getName();  
  39.             String firstLetter = name.substring(01).toUpperCase();  
  40.               
  41.             //获得属性的set、get的方法名  
  42.             String getMethodName = "get" + firstLetter + name.substring(1);  
  43.             String setMethodName = "set" + firstLetter + name.substring(1);  
  44.               
  45.             Method getMethod = classType.getMethod(getMethodName, new Class<?>[]{});  
  46.             Method setMethod = classType.getMethod(setMethodName, new Class<?>[]{field.getType()});  
  47.               
  48.             //获得copy对象的属性值  
  49.             Object value = getMethod.invoke(object, new Object[]{});  
  50.               
  51.             //设置被copy对象的属性值  
  52.             setMethod.invoke(objectCopy, value);  
  53.         }  
  54.         return objectCopy;  
  55.     }  
  56. }  
  57.   
  58. //JavaBean  
  59. class Person{  
  60.     private Long id;  
  61.     private String name;  
  62.     private int age;  
  63.       
  64.     //每个JavaBean都应该实现无参构造方法  
  65.     public Person() {}  
  66.       
  67.     public Person(String name, int age){  
  68.         this.name = name;  
  69.         this.age = age;  
  70.     }  
  71.   
  72.     //setter、getter方法     
  73. }  
1 0