Is it possible to write a Java generics expression that allows a subtype of a type and the type itself?
Given the following situation it's only possible to write a model handler which works on Specifi开发者_如何学CcModel
, it's not possible to have a model handler which handles only models. But when we remove the T extends Model
expression, it would be much to easy to create something illegal.
public interface Model {}
public class SpecificModel implements Model {}
public interface ModelHandler<T extends Model>
{
void handleModel(T model);
}
Is it possible to write a construct like T extends Model || Model
? So T
must either extend Model
or must be a Model
itself if the handler doesn't know a subtype of Model
?
Thank you!
Quote from Effective Java, by Joshua Bloch about the <? extends E>
notation:
The use of the keyword extends is slightly misleading: recall [from Item 26] that subtype is defined so that every type is a subtype of itself, even though it does not extend itself.
Therefore writing <T extends Model>
is equivalent to what you expect: <T extends Model || Model>
.
T extends Model
matches Model
. So, you can create a ModelHandler<Model>
here.
The terminology is, admittedly, slightly misleading.
(Or is your goal to write a ModelHandler<any subtype of Model but not Model itself>
?)
If T extends Model
then T
is a Model
. I'm really not sure what you want to write here... Also -- in generics the extends
also stands for implements
meaningwise.
精彩评论