Home >Java >javaTutorial >Restrictions on the Use of Generics

Restrictions on the Use of Generics

Barbara Streisand
Barbara StreisandOriginal
2024-12-30 21:25:14407browse

Restrições ao Uso de Genéricos

Generics in Java offer flexibility and security, but have some important restrictions. These involve instantiation of type parameters, static members, generic arrays and generic exceptions.

1. Instantiation of Type Parameters

  • You cannot create an instance directly from a type parameter.

Invalid example:

class Gen<T> {
    T ob;

    Gen() {
        ob = new T(); // Inválido!
    }
}

  • Reason: The compiler doesn't know what real type T represents as it's just a placeholder.
  • Workaround: Use an object factory or take the already created instance as an argument.

2. Restrictions on static Members
Static members cannot use generic type parameters of the outer class.

Invalid example:

class Wrong<T> {
    static T ob;          // Inválido!
    static T getob() {    // Inválido!
        return ob;
    }
}

Reason: Static context is shared among all instances of the class, while generic parameters can vary from one instance to another.
Workaround: Declare static methods that define their own type parameters:

static <U> U genericMethod(U value) {
    return value;
}

3. Generic Arrays
Constraints with arrays and generics:

  • It is not possible to instantiate a generic type array.
T vals[];        // Válido como referência
vals = new T[10]; // Inválido!

  • It is not possible to create type-specific generic reference arrays
Gen<Integer> gens[] = new Gen<Integer>[10]; // Inválido!

Reason: During execution, erasure eliminates type information, making it impossible to create safe arrays.
Workaround:

Use existing arrays:

vals = nums; // Atribuir array existente é válido.

  • Use wildcards
Gen<?> gens[] = new Gen<?>[10]; // Correto.

4. Generic Exceptions
A generic class cannot extend Throwable.
Invalid example:

class GenException<T> extends Exception { // Inválido!
    T value;
}

Reason: This could compromise the exception handling mechanism at runtime.
Solution: Use normal generic classes to encapsulate information and then integrate them with standard exceptions.

5. Summary of Restrictions
Instanciation of type parameters: Cannot instantiate directly, but you can use existing instances.
Static members: Cannot use generic types of the outer class, but static methods can define their own generic parameters.
Generic arrays: Cannot be instantiated directly, but generic references with wildcards are allowed.
Generic exceptions: Cannot be created, but can be simulated using normal classes.

Understanding these limitations is essential for designing safe and efficient generic classes in Java.

The above is the detailed content of Restrictions on the Use of Generics. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn