Java SE 7中不可恢复类型的变量 - 如何?

时间:2012-05-12 00:59:08

标签: java generics variadic-functions

我的代码在Java SE 7中发出警告。如何绕过它没有使用注释来抑制警告;按照预期 varargs:

  import java.util.Iterator;

  public class UnionIterator < E > implements Iterator < E > {

  public static < E > Iterator < E > newInstance (Iterator < E > ... iterators) {
    return new UnionIterator < E >(iterators);
  }

  private Iterator < E > [] iterators;

  private UnionIterator (Iterator < E > ... iterators) {
    this.iterators = iterators;
  }

  @Override
  public boolean hasNext() {
    // TODO
    return false;
  }

  @Override
  public E next() {
    // TODO
    return null;
  }

  @Override
  public void remove() {
    // TODO
  }

}

这是警告:

$ javac UnionIterator.java 
Note: UnionIterator.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
$ javac -Xlint:unchecked UnionIterator.java 
UnionIterator.java:5: warning: [unchecked] Possible heap pollution from parameterized vararg type Iterator<E>
  public static < E > Iterator < E > newInstance (Iterator < E > ... iterators) {
                                                                     ^
  where E is a type-variable:
    E extends Object declared in method <E>newInstance(Iterator<E>...)
UnionIterator.java:11: warning: [unchecked] Possible heap pollution from parameterized vararg type Iterator<E>
  private UnionIterator (Iterator < E > ... iterators) {
                                            ^
  where E is a type-variable:
    E extends Object declared in class UnionIterator
2 warnings

1 个答案:

答案 0 :(得分:5)

你做不到。如果您使用的是Java 7,则可以使用工厂方法上的@SafeVarargs注释来禁止每次调用newInstance时发出警告。