Home >Java >javaTutorial >Restrictions on the Use of Generics
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
Invalid example:
class Gen<T> { T ob; Gen() { ob = new T(); // Inválido! } }
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:
T vals[]; // Válido como referência vals = new T[10]; // Inválido!
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.
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!