[英]Can we force a Generic type to accept its parameterized type as only concrete child subclasses of a type and not that type itself
[英]Can I force a constructor to put a stricter bound on its generic type?
在Java中,泛型類具有用於構造某些泛型類型的實例的構造函數。 這很簡單,構造函數的調用者可以指定范圍內的任何類型。
是否有可能在該泛型類型上設置更嚴格的界限的構造函數?
例如,有一個強制將泛型類型設置為String
的構造函數。
public class GenericClass<T extends Serializable> {
public GenericClass() {
// normal constructor
}
public GenericClass(String argument) {
// Can I force this constructor to construct a `GenericClass<String>`?
}
}
// The first constructor can have any type
GenericClass<String> stringInstance = new GenericClass<>();
GenericClass<Integer> intInstance = new GenericClass<>();
// The second constructor is limited to `GenericClass<String>`
stringInstance = new GenericClass<>("with generic type String is okay");
intInstance = new GenericClass<>("with other generic type is not okay");
我想讓最后一行由於類型不兼容而失敗。
這可能嗎?
public GenericClass(String argument)
問題是編譯器應該如何知道String
為T
? 參數與泛型類型參數之間沒有鏈接,也無法指定一個。 你可以用
public GenericClass(T argument)
並用
new GenericClass<>("foo");
但這將允許使用任何類型的對象實例化GenericClass
。
盡管需要引入第二個類,但可以使用繼承大致實現所需的功能:
class GenericClass<T extends Serializable> {
public GenericClass() {
}
}
class StringClass extends GenericClass<String> {
public StringClass(String argument) {
}
}
如果要避免使用繼承,可以引入一個接口並使兩個類都實現該接口。 那就是我要做的。
導致最后一行失敗的一種方法是:
public class GenericClass<T extends Serializable> {
public GenericClass() {
// normal constructor
}
public GenericClass(T argument) {
}
}
但這顯然不會阻止人們調用new GenericClass<>(1)
。
或者,您可以編寫工廠方法ofString
:
public static GenericClass<String> ofString(String s) {
GenericClass<String> gc = new GenericClass<>();
// do stuff to gc
return gc;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.