Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Java 反射機制實作範例:動態建立物件與呼叫方法

一、範例目標

1. 依傳入的完整類別名字串,建立對應類別的實例。
2. 依傳入的物件實例與方法名字串,動態呼叫指定方法並取得回傳值。
3. 在 FanSheTest 單元測試中,傳入 "cn.com.rwq.test.Entity" 建立 Entity 物件,並動態呼叫與字串同名的方法。

二、程式碼

1. 測試類別

package cn.com.rwq.test;

import junit.framework.TestCase;

public class FanSheTest extends TestCase {
    private FanShe fanShe;

    @Override
    protected void setUp() throws Exception {
        super.setUp();
        fanShe = new FanShe();
    }

    public void testCreateClass() throws Exception {
        Object object = fanShe.createClass("cn.com.rwq.test.Entity");
        assertNotNull(object);
        Common common = (Common) object;
        assertEquals("123456789", common.getName());
        assertEquals("12345678", ((Entity) object).toString());
    }

    public void testCreateObject() throws Exception {
        Object object = fanShe.createClass("cn.com.rwq.test.Entity");
        fanShe.createObject(object, "print");

        String a = (String) fanShe.createObject(object, "strPrint");
        assertEquals("abs", a);

        int b = (int) fanShe.createObject(object, "intPrint");
        assertEquals(123, b);

        Common common = (Common) object;
        fanShe.createObject(common, "printName");
    }
}

2. 反射的實作

package cn.com.rwq.test;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class FanShe {

    /** 依完整類別名建立對應類別的實體 */
    public Object createClass(String className)
            throws ClassNotFoundException, InstantiationException, IllegalAccessException {
        Class clazz = Class.forName(className);
        Method m[] = clazz.getDeclaredMethods();
        for (Method one : m) {
            System.out.println(one.toString());
        }
        Object object = clazz.newInstance();
        return object;
    }

    /** 依物件與方法名,動態呼叫方法並回傳結果 */
    public static Object createObject(Object object, String actionName)
            throws ClassNotFoundException, InstantiationException, IllegalAccessException {
        Method aMethod;
        try {
            aMethod = object.getClass().getMethod(actionName, null);
            return aMethod.invoke(object, null);
        } catch (NoSuchMethodException | SecurityException e1) {
            e1.printStackTrace();
        } catch (IllegalArgumentException | InvocationTargetException e) {
            e.printStackTrace();
        }
        return null;
    }
}

3. JavaBean

package cn.com.rwq.test;

public class Entity extends Common {

    public Entity() {
        System.out.println("Entity 建構方法");
    }

    public void print() {
        System.out.println("執行 print,無回傳值");
    }

    void two() {
        System.out.println("執行 two 方法");
    }

    private void siyou() {
        System.out.println("執行 siyou 私有方法");
    }

    public String strPrint() {
        System.out.println("執行 strPrint,有回傳值");
        return "abs";
    }

    public int intPrint() {
        System.out.println("執行 intPrint,有回傳值");
        return 123;
    }

    public void printName() {
        System.out.println("11111111  " + super.getName());
    }

    public String toString() {
        return "12345678";
    }
}

4. 父類別

package cn.com.rwq.test;

public class Common {
    private String name = "123456789";

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

三、重點整理

1. 待反射的實體類別必須具備無參數建構子,因為 newInstance() 走的就是它。
2. Class<?> demo = Class.forName("...") 可依完整類別名字串取得指定的類別物件。
3. 取得一個類別的完整結構:

Class<?> demo = Class.forName("cn.com.rwq.test.Entity");

// 本類宣告的所有欄位
Field[] field = demo.getDeclaredFields();
for (int i = 0; i < field.length; i++) {
    int mo = field[i].getModifiers();          // 權限修飾符
    String priv = Modifier.toString(mo);
    Class<?> type = field[i].getType();        // 欄位型別
    System.out.println(priv + " " + type.getName() + " " + field[i].getName() + ";");
}

// 包含繼承而來或介面定義的公開欄位
Field[] filed1 = demo.getFields();
for (int j = 0; j < filed1.length; j++) {
    int mo = filed1[j].getModifiers();
    String priv = Modifier.toString(mo);
    Class<?> type = filed1[j].getType();
    System.out.println(priv + " " + type.getName() + " " + filed1[j].getName() + ";");
}

4. 呼叫方法:getMethod 只能取得 public 方法,若要碰非 public 方法必須改用 getDeclaredMethod 並呼叫 setAccessible(true)。

// 呼叫無參數方法
Method method = demo.getMethod("方法名");
method.invoke(demo.newInstance());

// 呼叫有參數的方法
method = demo.getMethod("方法名", String.class, int.class);
method.invoke(demo.newInstance(), "Rollen", 20);

補充一點:範例中 getMethod(actionName, null) 這種寫法在舊版 JDK 可以通過,新版編譯器會要求改寫成不帶第二個參數的 getMethod(actionName),語意完全相同。

Copyright © Linux教程網 All Rights Reserved