浅谈Java反射机制

openkk 12年前

一 从一个实例出发--在运行时获取某个对象相关信息

1. 我们首先定义一个Customer类,表示客户的相关信息

public  class Customer {    private Long id;    private String name;    private int age;    private String phone;    public Customer() {         }    public Customer(Long id,String name,int age,String phone) {     this.id=id;     this.name=name;     this.age=age;     this.phone=phone;    }    public final Long getId() {     return id;    }    public void setId(Long id) {     this.id=id;    }    public final String getName() {     return name;    }    public final void setName(String name) {     this.name=name;    }    public final int getAge() {     return age;    }    public void setAge(int age) {     this.age=age;    }    public final String getPhone() {     return phone;    }    public void setAge(String phone) {     this.phone=phone;    }   }
2. 现在我们写一个类,实现获取Customer实例所有的构造方法和普通方法及属性信息
import java.lang.reflect.Constructor;  import java.lang.reflect.Field;  import java.lang.reflect.Method;    public class ReflectionApplication {     /**    * @param args    */   public static void ShowObjectInfo(Object obj) throws Exception {    Class c=obj.getClass();    int i;    System.out.println(obj.toString()+"所有的构造方法是:");    Constructor [] cs=c.getConstructors();    for(i=0;i<cs.length;i++) {     System.out.println(cs[i].toString());    }        System.out.println(obj.toString()+"所有的声明的方法是:");    Method [] methods=c.getDeclaredMethods();    for(i=0;i<methods.length;i++) {     System.out.println(methods[i].toString());    }        System.out.println(obj.toString()+"所有的声明的属性是:");    Field[] fields=c.getDeclaredFields();    for(i=0;i<fields.length;i++) {     System.out.println(fields[i].toString());    }   }   public static void main(String[] args) throws Exception {    // TODO Auto-generated method stub    Customer customer=new Customer(001L,"wangzhicheng",28,"13866916216");    ShowObjectInfo(customer);   }    }
 3. 运行结果是:
Customer@1fb8ee3所有的构造方法是:  public Customer()  public Customer(java.lang.Long,java.lang.String,int,java.lang.String)  Customer@1fb8ee3所有的声明的方法是:  public void Customer.setId(java.lang.Long)  public final int Customer.getAge()  public void Customer.setAge(int)  public void Customer.setAge(java.lang.String)  public final java.lang.String Customer.getPhone()  public final java.lang.String Customer.getName()  public final java.lang.Long Customer.getId()  public final void Customer.setName(java.lang.String)  Customer@1fb8ee3所有的声明的属性是:  private java.lang.Long Customer.id  private java.lang.String Customer.name  private int Customer.age  private java.lang.String Customer.phone  private java.lang.String Customer.phone