My Blog

My WordPress Blog

My Blog

My WordPress Blog

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&lt;String&gt; stringBox = new Box&lt;String&gt;();
  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.
No Instance

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top