1. 程式人生 > >java反射機制簡單例子

java反射機制簡單例子

package com.yemaozi.reflect;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class ReflectTest {
    /**
    * 通過java的反射機制獲取類的所有屬性和方法
    */
    public void test1() {
        try {
            Class c = Class.forName("com.yemaozi.reflect.Customer");
            System.out.println("屬性:");
            Field f[] = c.getDeclaredFields();
            for (int i = 0; i < f.length; i++) {
                System.out.println(f[i].getName());
            }
            System.out.println("方法:");
            Method m[] = c.getDeclaredMethods();
            for (int i = 0; i < m.length; i++) {
                System.out.println(m[i].toString());
            }

        } catch (Throwable e) {
            System.err.println(e);
        }
    }

    /**
    * 通過java的反射機制動態修改物件的屬性
    * @param o
    */
    public void test2(Customer o) {

        try {
            Class c = o.getClass();
            //getMethod方法第一個引數指定一個需要呼叫的方法名稱,第二個引數是需要呼叫方法的引數型別列表,如無引數可以指定null,該方法返回一個方法物件 
            Method sAge = c.getMethod("setAge", new Class[] { int.class });
            Method gAge = c.getMethod("getAge", null);
            Method sName = c.getMethod("setName", new Class[] { String.class });
            //動態修改Customer物件的age
            Object[] args1 = { new Integer(25) };
            sAge.invoke(o, args1);
            //動態取得Customer物件的age
            Integer AGE = (Integer) gAge.invoke(o, null);
            System.out.println("the Customer age is: " + AGE.intValue());
            //動態修改Customer物件的name
            Object[] args2 = { new String("李四") };
            sName.invoke(o, args2);

        } catch (Throwable e) {
            System.err.println(e);
        }
    }
    /**
    * 通過java的反射機制做一個簡單物件的克隆
    * @param o
    * @return
    */
    public Object test3(Customer o) {
        Object o2 = null;
        try {
            Class c = o.getClass();
            //通過預設構造方法建立一個新的物件
            o2 = c.getConstructor(new Class[] {}).newInstance(
                    new Object[] {});
            Field fields[] = c.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 = c.getMethod(getMethodName, new Class[] {});
                // 獲得和屬性對應的setXXX()方法
                Method setMethod = c.getMethod(setMethodName, new Class[] { field.getType() });
                // 呼叫原物件的getXXX()方法
                Object value = getMethod.invoke(o, new Object[] {});
                // 呼叫拷貝物件的setXXX()方法
                setMethod.invoke(o2, new Object[] { value });
            }
        } catch (Throwable e) {
            System.err.println(e);
        }
        return o2;
    }

    public static void main(String[] args) throws Exception {
        ReflectTest t = new ReflectTest();
        t.test1();
        Customer customer = new Customer();
        customer.setAge(20);
        customer.setName("張三");
        System.out.println("呼叫前name: " + customer.getName());
        System.out.println("呼叫前age: " + customer.getAge());
        t.test2(customer);
        System.out.println("呼叫後name: " + customer.getName());
        System.out.println("呼叫後age: " + customer.getAge());
        Customer customer2 = (Customer)t.test3(customer);
        System.out.println("克隆物件的name: " + customer2.getName());
        System.out.println("克隆物件的age: " + customer2.getAge());
    }
}

class Customer {
    private long id;
    private String name;
    private int age;

    public Customer() {
    }
    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;
    }
}

執行結果:
屬性:
id
name
age
方法:
public java.lang.String demo1.client.Customer.getName()
public long demo1.client.Customer.getId()
public void demo1.client.Customer.setName(java.lang.String)
public void demo1.client.Customer.setAge(int)
public int demo1.client.Customer.getAge()
public void demo1.client.Customer.setId(long)
呼叫前name: 張三
呼叫前age: 20
the Customer age is: 25
呼叫後name: 李四
呼叫後age: 25
克隆物件的name: 李四
克隆物件的age: 25