Java Generics - No Instance


Advertisements

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.

Useful Video Courses


Video

Java Date and Time Online Training

16 Lectures 2 hours

Malhar Lathkar

Video

Java Servlet Online Training

19 Lectures 5 hours

Malhar Lathkar

Video

JavaScript Online Training

25 Lectures 2.5 hours

Anadi Sharma

Video

Java Online Training

Most Popular

126 Lectures 7 hours

Tushar Kale

Video

Java Essential Training

119 Lectures 17.5 hours

Monica Mittal

Video

Java Essentials Online Training

76 Lectures 7 hours

Arnab Chakraborty

Advertisements