简体   繁体   English

你能定义一个具有下限和上限的泛型边界吗?

[英]Can you define a generic bound that both has lower and upper bounds?

Is it possible to define a generic bound that: 是否可以定义一个通用绑定:

  • implements an interface SomeInterface 实现一个接口SomeInterface
  • is a superclass of some class MyClass 是一些MyClass类的超类

Something like: 就像是:

Collection<? extends SomeInterface & super MyClass> c; // doesn't compile

According to the spec , the answer would be no (you can have super or extends , but not both): 根据规范 ,答案是否定的(你可以有superextends ,但不是两者):

 TypeArguments: TypeArguments:\n    < TypeArgumentList > <TypeArgumentList>\n\nTypeArgumentList: TypeArgumentList: \n    TypeArgument TypeArgument\n    TypeArgumentList , TypeArgument TypeArgumentList,TypeArgument\n\nTypeArgument: TypeArgument:\n    ReferenceType 引用类型\n    Wildcard 通配符\n\nWildcard: 通配符:\n    ?  WildcardBounds opt WildcardBounds 选择\n\nWildcardBounds: WildcardBounds:\n    extends ReferenceType 扩展ReferenceType\n    super ReferenceType 超级ReferenceType 

You cannot use generic type ( T in your case) with bounds when declaring a variable. 在声明变量时,不能使用带有边界的泛型类型(在您的情况下为T )。

It should be either a wildcard ( ? ), or just use the full generic type of the class. 它应该是通配符( ? ),或者只使用类的完整泛型类型。

Eg 例如

// Here only extends is allowed
class My< T extends SomeInterface >
{

  // If using T, then no bounds are allowed
  private Collection<T> var1;

  private Collection< ? extends SomeInterface > var2;

  // Cannot have extends and super on the same wildcard declaration
  private Collection< ? super MyClass > var3;

  // You can use T as a bound for wildcard
  private Collection< ? super T > var4;

  private Collection< ? extends T > var5;

}

In some cases, you may tighten the declaration by adding extra generic parameter to a class (or method) and adding a bound on that particular parameter: 在某些情况下,您可以通过向类(或方法)添加额外的泛型参数并在该特定参数上添加绑定来收紧声明:

class My <
  T extends MyClass< I >,
  I extends SomeInterface 
>
{
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM