3

类型变量的边界只能出现在类、接口、方法和构造函数的声明中?

或者当它们用作类型参数时我可以绑定类型变量吗?

编辑: 示例:

class MyClass<T extends Number> { // T is bounded by the interface Number
    // can a bounded Type Parameter appear anywhere else,
    // besides the Type parameter declaration?
}
4

3 回答 3

2

考虑这个静态方法:

public static <T> List<T> filter(final List<T> orig, final Predicate<T> pred) {
  return new ArrayList<T>() {{
    for (T t : orig) if (pred.allow(t)) add(t);
  }};
}

“T”的“值”被每次调用“绑定”。现在,在调用方法时它并没有真正绑定;通过检查每个调用的静态细节,它在编译时被“绑定”,因为它出现在其他地方。

因此,如果在某个地方我这样称呼它:

final List<Integer> numbers = Whatever.filter(origList, new Predicate<Integer>() {
  public boolean allow(Integer i) {
    return i != null && i.intValue() > 0;
  }
});

那么“T”就是“整数”。

于 2011-01-23T15:35:33.870 回答
2

Java 语言规范似乎同意您的看法:

类型变量(第 4.4 节)是不合格的标识符。类型变量由泛型类声明 (§8.1.2) 泛型接口声明 (§9.1.2) 泛型方法声明 (§8.4.4) 和泛型构造函数声明 (§8.8.4) 引入。

于 2011-01-23T15:40:51.573 回答
1

是的。类型边界应用于类型变量的声明。

换句话说 - 当类型变量第一次出现时。

public class MyClass<T extends MyItem> { // <- Type declaration

   private T item; // <-  Type usage

   public <K extends T> K getSubitem() {
   //      ^            ^ 
   //  declaration    usage   
     ...
     Arrays.<K>asList(); // <- Type Usage not a type declaration
   } 

}
于 2011-01-23T15:57:43.977 回答