重温Java经典教程(The Java™ Tutorials)第三篇-Java语言-第二章-2.6.2泛型

Wildcards(通配符)

In generic code, the question mark (?), called the wildcard, represents an unknown type. The wildcard can be used in a variety of situations: as the type of a parameter, field, or local variable; sometimes as a return type (though it is better programming practice to be more specific). The wildcard is never used as a type argument for a generic method invocation, a generic class instance creation, or a supertype.

The following sections discuss wildcards in more detail, including upper bounded wildcards, lower bounded wildcards, and wildcard capture.

Wildcards and Subtyping

As described in Generics, Inheritance, and Subtypes, generic classes or interfaces are not related merely because there is a relationship between their types. However, you can use wildcards to create a relationship between generic classes or interfaces.

Given the following two regular (non-generic) classes:

class A { /* ... */ }
class B extends A { /* ... */ }

It would be reasonable to write the following code:

B b = new B();
A a = b;

This example shows that inheritance of regular classes follows this rule of subtyping: class B is a subtype of class A if B extends A. This rule does not apply to generic types:

List lb = new ArrayList<>();
List la = lb;   // compile-time error

Given that Integer is a subtype of Number, what is the relationship between List and List?

重温Java经典教程(The Java™ Tutorials)第三篇-Java语言-第二章-2.6.2泛型_第1张图片

The common parent is List.

Although Integer is a subtype of Number, List is not a subtype of List and, in fact, these two types are not related. The common parent of List and List is List.

In order to create a relationship between these classes so that the code can access Number's methods through List's elements, use an upper bounded wildcard:

List intList = new ArrayList<>();
List  numList = intList;  // OK. List is a subtype of List

Because Integer is a subtype of Number, and numList is a list of Number objects, a relationship now exists between intList (a list of Integer objects) and numList. The following diagram shows the relationships between several List classes declared with both upper and lower bounded wildcards.

重温Java经典教程(The Java™ Tutorials)第三篇-Java语言-第二章-2.6.2泛型_第2张图片

A hierarchy of several generic List class declarations.

The Guidelines for Wildcard Use section has more information about the ramifications of using upper and lower bounded wildcards.

Non-Reifiable Types(不可再流通类型)

The section Type Erasure discusses the process where the compiler removes information related to type parameters and type arguments. Type erasure has consequences related to variable arguments (also known as varargs ) methods whose varargs formal parameter has a non-reifiable type. See the section Arbitrary Number of Arguments in Passing Information to a Method or a Constructor for more information about varargs methods.

This page covers the following topics:

  • Non-Reifiable Types
  • Heap Pollution
  • Potential Vulnerabilities of Varargs Methods with Non-Reifiable Formal Parameters
  • Preventing Warnings from Varargs Methods with Non-Reifiable Formal Parameters

Non-Reifiable Types

reifiable type is a type whose type information is fully available at runtime. This includes primitives, non-generic types, raw types, and invocations of unbound wildcards.

Non-reifiable types are types where information has been removed at compile-time by type erasure — invocations of generic types that are not defined as unbounded wildcards. A non-reifiable type does not have all of its information available at runtime. Examples of non-reifiable types are List and List; the JVM cannot tell the difference between these types at runtime. As shown in Restrictions on Generics, there are certain situations where non-reifiable types cannot be used: in an instanceofexpression, for example, or as an element in an array.

Heap Pollution

Heap pollution occurs when a variable of a parameterized type refers to an object that is not of that parameterized type. This situation occurs if the program performed some operation that gives rise to an unchecked warning at compile-time. An unchecked warning is generated if, either at compile-time (within the limits of the compile-time type checking rules) or at runtime, the correctness of an operation involving a parameterized type (for example, a cast or method call) cannot be verified. For example, heap pollution occurs when mixing raw types and parameterized types, or when performing unchecked casts.

In normal situations, when all code is compiled at the same time, the compiler issues an unchecked warning to draw your attention to potential heap pollution. If you compile sections of your code separately, it is difficult to detect the potential risk of heap pollution. If you ensure that your code compiles without warnings, then no heap pollution can occur.

Potential Vulnerabilities of Varargs Methods with Non-Reifiable Formal Parameters

Generic methods that include vararg input parameters can cause heap pollution.

Consider the following ArrayBuilder class:

public class ArrayBuilder {

  public static  void addToList (List listArg, T... elements) {
    for (T x : elements) {
      listArg.add(x);
    }
  }

  public static void faultyMethod(List... l) {
    Object[] objectArray = l;     // Valid
    objectArray[0] = Arrays.asList(42);
    String s = l[0].get(0);       // ClassCastException thrown here
  }

}

The following example, HeapPollutionExample uses the ArrayBuiler class:

public class HeapPollutionExample {

  public static void main(String[] args) {

    List stringListA = new ArrayList();
    List stringListB = new ArrayList();

    ArrayBuilder.addToList(stringListA, "Seven", "Eight", "Nine");
    ArrayBuilder.addToList(stringListB, "Ten", "Eleven", "Twelve");
    List> listOfStringLists =
      new ArrayList>();
    ArrayBuilder.addToList(listOfStringLists,
      stringListA, stringListB);

    ArrayBuilder.faultyMethod(Arrays.asList("Hello!"), Arrays.asList("World!"));
  }
}

When compiled, the following warning is produced by the definition of the ArrayBuilder.addToList method:

warning: [varargs] Possible heap pollution from parameterized vararg type T

When the compiler encounters a varargs method, it translates the varargs formal parameter into an array. However, the Java programming language does not permit the creation of arrays of parameterized types. In the method ArrayBuilder.addToList, the compiler translates the varargs formal parameter T... elements to the formal parameter T[] elements, an array. However, because of type erasure, the compiler converts the varargs formal parameter to Object[] elements. Consequently, there is a possibility of heap pollution.

The following statement assigns the varargs formal parameter l to the Object array objectArgs:

Object[] objectArray = l;

This statement can potentially introduce heap pollution. A value that does match the parameterized type of the varargs formal parameter l can be assigned to the variable objectArray, and thus can be assigned to l. However, the compiler does not generate an unchecked warning at this statement. The compiler has already generated a warning when it translated the varargs formal parameter List... l to the formal parameter List[] l. This statement is valid; the variable l has the type List[], which is a subtype of Object[].

Consequently, the compiler does not issue a warning or error if you assign a List object of any type to any array component of the objectArray array as shown by this statement:

objectArray[0] = Arrays.asList(42);

This statement assigns to the first array component of the objectArray array with a List object that contains one object of type Integer.

Suppose you invoke ArrayBuilder.faultyMethod with the following statement:

ArrayBuilder.faultyMethod(Arrays.asList("Hello!"), Arrays.asList("World!"));

At runtime, the JVM throws a ClassCastException at the following statement:

// ClassCastException thrown here
String s = l[0].get(0);

The object stored in the first array component of the variable l has the type List, but this statement is expecting an object of type List.

Prevent Warnings from Varargs Methods with Non-Reifiable Formal Parameters

If you declare a varargs method that has parameters of a parameterized type, and you ensure that the body of the method does not throw a ClassCastException or other similar exception due to improper handling of the varargs formal parameter, you can prevent the warning that the compiler generates for these kinds of varargs methods by adding the following annotation to static and non-constructor method declarations:

@SafeVarargs

The @SafeVarargs annotation is a documented part of the method's contract; this annotation asserts that the implementation of the method will not improperly handle the varargs formal parameter.

It is also possible, though less desirable, to suppress such warnings by adding the following to the method declaration:

@SuppressWarnings({"unchecked", "varargs"})

However, this approach does not suppress warnings generated from the method's call site. If you are unfamiliar with the @SuppressWarnings syntax, see Annotations.

Restrictions on Generics(重点了解)

To use Java generics effectively, you must consider the following restrictions:

  • Cannot Instantiate Generic Types with Primitive Types
  • Cannot Create Instances of Type Parameters
  • Cannot Declare Static Fields Whose Types are Type Parameters
  • Cannot Use Casts or instanceof With Parameterized Types
  • Cannot Create Arrays of Parameterized Types
  • Cannot Create, Catch, or Throw Objects of Parameterized Types
  • Cannot Overload a Method Where the Formal Parameter Types of Each Overload Erase to the Same Raw Type

Cannot Instantiate Generic Types with Primitive Types

Consider the following parameterized type:

class Pair {

    private K key;
    private V value;

    public Pair(K key, V value) {
        this.key = key;
        this.value = value;
    }

    // ...
}

When creating a Pair object, you cannot substitute a primitive type for the type parameter K or V:

Pair<int, char> p = new Pair<>(8, 'a');  // compile-time error

You can substitute only non-primitive types for the type parameters K and V:

Pair<Integer, Character> p = new Pair<>(8, 'a');

Note that the Java compiler autoboxes 8 to Integer.valueOf(8) and 'a' to Character('a'):

Pair p = new Pair<>(Integer.valueOf(8), new Character('a'));

For more information on autoboxing, see Autoboxing and Unboxing in the Numbers and Strings lesson.

Cannot Create Instances of Type Parameters

You cannot create an instance of a type parameter. For example, the following code causes a compile-time error:

public static  void append(List list) {
    E elem = new E();  // compile-time error
    list.add(elem);
}

As a workaround, you can create an object of a type parameter through reflection:

public static  void append(List list, Class cls) throws Exception {
    E elem = cls.newInstance();   // OK
    list.add(elem);
}

You can invoke the append method as follows:

List ls = new ArrayList<>();
append(ls, String.class);

Cannot Declare Static Fields Whose Types are Type Parameters

A class's static field is a class-level variable shared by all non-static objects of the class. Hence, static fields of type parameters are not allowed. Consider the following class:

public class MobileDevice {
    private static T os;

    // ...
}

If static fields of type parameters were allowed, then the following code would be confused:

MobileDevice phone = new MobileDevice<>();
MobileDevice pager = new MobileDevice<>();
MobileDevice pc = new MobileDevice<>();

Because the static field os is shared by phone, pager, and pc, what is the actual type of os? It cannot be Smartphone, Pager, and TabletPC at the same time. You cannot, therefore, create static fields of type parameters.

Cannot Use Casts or instanceof with Parameterized Types

Because the Java compiler erases all type parameters in generic code, you cannot verify which parameterized type for a generic type is being used at runtime:

public static  void rtti(List list) {
    if (list instanceof ArrayList) {  // compile-time error
        // ...
    }
}

The set of parameterized types passed to the rtti method is:

S = { ArrayList, ArrayList LinkedList, ... }

The runtime does not keep track of type parameters, so it cannot tell the difference between an ArrayList and an ArrayList. The most you can do is to use an unbounded wildcard to verify that the list is an ArrayList:

public static void rtti(List list) {
    if (list instanceof ArrayList) {  // OK; instanceof requires a reifiable type
        // ...
    }
}

Typically, you cannot cast to a parameterized type unless it is parameterized by unbounded wildcards. For example:

List li = new ArrayList<>();
List  ln = (List) li;  // compile-time error

However, in some cases the compiler knows that a type parameter is always valid and allows the cast. For example:

List l1 = ...;
ArrayList l2 = (ArrayList)l1;  // OK

Cannot Create Arrays of Parameterized Types

You cannot create arrays of parameterized types. For example, the following code does not compile:

List[] arrayOfLists = new List[2];  // compile-time error

The following code illustrates what happens when different types are inserted into an array:

Object[] strings = new String[2];
strings[0] = "hi";   // OK
strings[1] = 100;    // An ArrayStoreException is thrown.

If you try the same thing with a generic list, there would be a problem:

Object[] stringLists = new List[];  // compiler error, but pretend it's allowed
stringLists[0] = new ArrayList();   // OK
stringLists[1] = new ArrayList();  // An ArrayStoreException should be thrown,
                                            // but the runtime can't detect it.

If arrays of parameterized lists were allowed, the previous code would fail to throw the desired ArrayStoreException.

Cannot Create, Catch, or Throw Objects of Parameterized Types

A generic class cannot extend the Throwable class directly or indirectly. For example, the following classes will not compile:

// Extends Throwable indirectly
class MathException extends Exception { /* ... */ }    // compile-time error

// Extends Throwable directly
class QueueFullException extends Throwable { /* ... */ // compile-time error

A method cannot catch an instance of a type parameter:

public static  void execute(List jobs) {
    try {
        for (J job : jobs)
            // ...
    } catch (T e) {   // compile-time error
        // ...
    }
}

You can, however, use a type parameter in a throws clause:

class Parser {
    public void parse(File file) throws T {     // OK
        // ...
    }
}

Cannot Overload a Method Where the Formal Parameter Types of Each Overload Erase to the Same Raw Type

A class cannot have two overloaded methods that will have the same signature after type erasure.

public class Example {
    public void print(Set strSet) { }
    public void print(Set intSet) { }
}

The overloads would all share the same classfile representation and will generate a compile-time error.

你可能感兴趣的:(Java)