- Java Generics - Home
- Java Generics - Overview
- Java Generics - Environment Setup
- Examples - Generic Classes
- Java Generics - Generic Classes
- Type Parameter Naming Conventions
- Java Generics - Type inference
- Java Generics - Generic Methods
- Java Generics - Multiple Type
- Java Generics - Parameterized Types
- Java Generics - Raw Types
- Examples - Bounded Type
- Bounded Type Parameters
- Java Generics - Multiple Bounds
- Examples - Collections
- Java Generics - Generic List
- Java Generics - Generic Set
- Java Generics - Generic Map
- Examples - Wild Cards
- Upper Bounded Wildcards
- Generics - Unbounded Wildcards
- Lower Bounded Wildcards
- Generics - Guidelines for Wildcards
- Type Erasure
- Java Generics - Types Erasure
- Java Generics - Bound Types Erasure
- Unbounded Types Erasure
- Java Generics - Methods Erasure
- Restrictions on Generics
- Java Generics - No Primitive Types
- Java Generics - No Instance
- Java Generics - No Static field
- Java Generics - No Cast
- Java Generics - No instanceOf
- Java Generics - No Array
- Java Generics - No Exception
- Java Generics - No Overload
- Java Generics Useful Resources
- Java Generics - Quick Guide
- Java Generics - Useful Resources
- Java Generics - Discussion
Java Generics - No Instance
A type parameter cannot be used to instantiate its object inside a method.
public static <T> void add(Box<T> box) {
//compiler error
//Cannot instantiate the type T
//T item = new T();
//box.add(item);
}
To achieve such functionality, use reflection.
public static <T> void add(Box<T> box, Class<T> clazz)
throws InstantiationException, IllegalAccessException{
T item = clazz.newInstance(); // OK
box.add(item);
System.out.println("Item added.");
}
Example
package com.tutorialspoint;
public class GenericsTester {
public static void main(String[] args)
throws InstantiationException, IllegalAccessException {
Box<String> stringBox = new Box<String>();
add(stringBox, String.class);
}
public static <T> void add(Box<T> box) {
//compiler error
//Cannot instantiate the type T
//T item = new T();
//box.add(item);
}
public static <T> void add(Box<T> box, Class<T> clazz)
throws InstantiationException, IllegalAccessException{
T item = clazz.newInstance(); // OK
box.add(item);
System.out.println("Item added.");
}
}
class Box<T> {
private T t;
public void add(T t) {
this.t = t;
}
public T get() {
return t;
}
}
This will produce the following result −
Item added.
Advertisements