簡體   English   中英

從構造函數獲取通用參數的對象類型?

[英]Get type of Object from constructor for generic parameters?

private LinkedList register;

public Register(Object obj){
    register = new LinkedList<obj>();
}

因此,基本上可以通過此方法定義LinkedList應該包含的對象類型嗎? (對於Java)

也許obj.getClass?

泛型可能會造成混淆。 我想你想要這個:

public class Register<T> {
    private LinkedList<T> register = new LinkedList<T>();

    public static <T> Register<T> create(T object) {
        return new Register<T>();
    }
}

本質上沒有,泛型僅是編譯時,需要在某個地方聲明。

class Register<T> {
    LinkedList<T> register;

    Register(T obj) {
        register = new LinkedList<T>();
    }

例如,您可以使用工廠方法。

    static <U> Register<U> of(U obj) {
        Register<U> result = new Register<U>(obj);
        return result;
    }
}
Register<String> a = new Register<String>("abc");
Register<Double> b = Register.of(1.0d);

另請參閱課程:泛型

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM