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

Java 泛型擦除下「 new T()」的三種補救方案

不同於 C++ 可以直接寫出 T t = new T();,Java 因為型別擦除(Type Erasure)的關係,在編譯期根本拿不到 T 的實際型別,自然無法直接 new 出物件。本文整理了三種在 Java 中變通的解法,讓泛型也能「造」出实例。

方案一:傳入 Class 物件

把 Class<T> 傳進來,再呼叫 newInstance()。這種寫法簡單直觀,但缺點是若傳入的型別沒有無參數建構子(例如 Integer),錯誤要到執行期才會爆發,因此並不被官方所推薦。

方案二:傳入工廠物件

自訂一個 FactoryI<T> 介面,由外部注入對應的工廠來負責建立物件。這是最靈活、也最安全的做法,能妥善處理像 Integer 這類沒有預設建構子的型別。

方案三:樣板方法模式

用抽象類別把 create() 留給子類實作,在父類建構時呼叫。這也是《Think in Java》中介紹的經典手法。

public class CreatingTypesSolutions {
    public static void main(String[] args) {
        // 方案一:傳入 Class 物件
        ClassAsFactory<Employ> caf1 = new ClassAsFactory<Employ>(Employ.class);
        // ClassAsFactory<Integer> caf2 = new ClassAsFactory<Integer>(Integer.class);

        // 方案二:傳入工廠
        ClassAsFactory2<Employ> caf21 = new ClassAsFactory2<Employ>(new EmployFactory());
        ClassAsFactory2<Integer> caf22 = new ClassAsFactory2<Integer>(new IntegerFactory());

        // 方案三:樣板方法設計模式
        IntegerGeneric ig1 = new IntegerGeneric();
        System.out.println(ig1.create());
    }
}

class Employ {
}

class ClassAsFactory<T> {
    public ClassAsFactory(Class<T> t) {
        try {
            T tObj = t.newInstance();
            System.out.println(tObj.getClass().getSimpleName() + " object!");
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }
}

// 方案二:介面
interface FactoryI<T> {
    T create();
}

class ClassAsFactory2<T> {
    public <F extends FactoryI<T>> ClassAsFactory2(F factory) {
        System.out.println(factory.create().getClass().getSimpleName() + " create successful");
    }
}

class EmployFactory implements FactoryI<Employ> {
    public Employ create() {
        return new Employ();
    }
}

class IntegerFactory implements FactoryI<Integer> {
    public Integer create() {
        return new Integer(0);
    }
}

// 方案三:樣板方法設計模式
abstract class GenericWithCreate<T> {
    final T element;

    GenericWithCreate() {
        element = create();
    }

    abstract T create();
}

class IntegerGeneric extends GenericWithCreate<Integer> {
    @Override
    Integer create() {
        return new Integer("4");
    }
}

三種方案各有取捨:追求簡潔可用方案一,追求安全與彈性則首推方案二,而方案三則適合把「建立」這一步延後到子類的情境。

Copyright © Linux教程網 All Rights Reserved