在JDK中,主要由以下类来实现JAVA反射机制,这些类都位于java.lang.reflect包中。
Class类:代表一个类。
Field类:代表类的属性。
Method:代表类的方法。
Constructor类:代表类的构造方法。
下面的ReflectTester类演示了Reflection API的基本使用方法,ReflectTester类有一个copy(Object object)方法,这个方法能够创建一个和参数object同样类型的对象,然后把object对象中的所有属性拷贝到新建的对象中,并将它返回。
ReflectTester类:
- package mypack;
- import java.lang.reflect.Field;
- import java.lang.reflect.Method;
- public class ReflectTester {
- public Object copy(Object object)throws Exception{
- //获得对象类型
- Class classType=object.getClass();
- System.out.println("Class:"+classType.getName());
- //通过默认构造方法创建一个新的对象
- Object objectCopy=classType.getConstructor(new Class[]{}).newInstance(new Object[]{});
- //获得所有对象的属性
- Field fields[]=classType.getDeclaredFields();
- for(int i=0;i<fields.length;i++)
- {
- Field field=fields[i];
- String fieldName=field.getName();
- String firstLetter=fieldName.substring(0,1).toUpperCase();
- //获得和属性对应的getXXX()方法的名字
- String getMethodName="get"+firstLetter+fieldName.substring(1);
- //获得和属性对应的setXXX()方法的名字
- String setMethodName="set"+firstLetter+fieldName.substring(1);
- //获得和属性对应的getXXX()方法
- Method getMethod=classType.getMethod(getMethodName, new Class[]{});
- //获得和属性对应的setXXX()方法
- Method setMethod=classType.getMethod(setMethodName, new Class[]{field.getType()});
- //调用原对象的getXXX()方法
- Object value=getMethod.invoke(object, new Object[]{});
- System.out.println(fieldName+":"+value);
- //调用拷贝对象的setXXX()方法
- setMethod.invoke(objectCopy, new Object[]{value});
- }
- return objectCopy;
- }
- /**
- * @param args
- */
- public static void main(String[] args)throws Exception {
- Customer customer=new Customer("Tom",21);
- customer.setId(new Long(1));
- Customer customerCopy=(Customer)new ReflectTester().copy(customer);
- System.out.println("copy information: "+customerCopy.getName()+" "+customer.getAge());
- }
- }
Customer类:
- package mypack;
- public class Customer {
- private Long id;
- private String name;
- private int age;
- public Customer() {
- super();
- // TODO Auto-generated constructor stub
- }
- public Customer(String name,int age){
- this.name=name;
- this.age=age;
- }
- public Long getId() {
- return id;
- }
- public void setId(Long id) {
- this.id = id;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public int getAge() {
- return age;
- }
- public void setAge(int age) {
- this.age = age;
- }
- }
[注:]Customer类必须提供无参构造,否则运行ReflectTester类时会抛出如下异常:
Class:mypack.Customer
Exception in thread "main" java.lang.NoSuchMethodException: mypack.Customer.<init>()
at java.lang.Class.getConstructor0(Unknown Source)
at java.lang.Class.getConstructor(Unknown Source)
at mypack.ReflectTester.copy(ReflectTester.java:15)
at mypack.ReflectTester.main(ReflectTester.java:56)