簡體   English   中英

Java子類化問題與泛型類型的自引用類型

[英]Java subclassing issue with generic type of self-referential type

import java.util.*;

// Let's define a self-referential type:
class SelfReferential<T extends SelfReferential<T>> {}

//A complete (i.e. not parameterized) subtype of SelfReferential:
class SubclassA extends SelfReferential<SubclassA> {}

//A partial (i.e. parameterized) subtype of SelfReferential:
class SubclassB<T extends SubclassB<T>> extends SelfReferential<T> {}

//Two complete subtypes of SubclassB
class SubclassB1 extends SubclassB<SubclassB1> {}    
class SubclassB2 extends SubclassB<SubclassB2> {}

//Now let's define a generic type over SelfReferential:
class Generic<T extends SelfReferential<T>> {}

//No problem creating a subtype for A, B1 or B2
class GenericA extends Generic<SubclassA> {}   
class GenericB1 extends Generic<SubclassB1> {}    
class GenericB2 extends Generic<SubclassB2> {}

//We can also defined a parameterize type for specific types extending SubclassB
class GenericB<T extends SubclassB<T>> extends Generic<T> {}

//However, it does not seem possible to define a non-parameterized subtype of Generic of ANY subtype of SublassB
//My goal is to provide a type alias for GenericB<? extends SubclassB<?>> to avoid 
//having to mention it everywhere in the code. This is like providing an alias for ArrayList<String> using 
class ArrayListOfString extends ArrayList<String> {}

//Unsucessful attempts:
//class GenericAnyB extends Generic<SubclassB> {} //ERROR: bound mismatch
//class GenericAnyB extends Generic<SubclassB<?>> {} //ERROR: bound mismatch
//class GenericAnyB extends Generic<? extends SubclassB<?>> {} //ERROR: invalid syntax: a supertype cannot specify any wildcard
//class GenericAnyB extends Generic<SubclassB<? extends SubclassB>> {} //ERROR: bound mismatch
//class GenericAnyB extends Generic<SubclassB<SubclassB<SubclassB<SubclassB<SubclassB<SubclassB>>>>>> {} // well...
//class GenericAnyB extends <T extends SubclassB<T>> Generic<T> {} //ERROR: this syntax is illegal

最重要的是,我無法在extends子句中指定“引用循環”。

問題:這是Java語言限制嗎?

你是對的,這是不可能的,就像在沒有通配符或原始類型的情況下宣布具有自引用類型的變量一樣。 您將無法直接實例化SubclassB ,原因與您在沒有自引用類型參數的情況下不能將其用作綁定的原因相同。

有關此限制的更多討論,請參閱此文章: 具有流暢接口和繼承的自限泛型類型

底線是GenericAnyB本身需要通用才能使用SubclassB作為綁定:

class GenericAnyB<T extends SubclassB<T>> extends Generic<T> { }

在任何可用的東西之前,只需在層次結構中添加額外的步驟:

class GenericB1 extends GenericAnyB<SubclassB1> { }   
class GenericB2 extends GenericAnyB<SubclassB2> { }

暫無
暫無

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

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