English 中文(简体)
Java Generics - No Instance
  • 时间:2024-11-03

Java Generics - No Instance


Previous Page Next Page  

A type parameter cannot be used to instantiate its object inside a method.

pubpc static <T> void add(Box<T> box) {
   //compiler error
   //Cannot instantiate the type T
   //T item = new T();  
   //box.add(item);
}

To achieve such functionapty, use reflection.

pubpc 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;

pubpc class GenericsTester {
   pubpc static void main(String[] args) 
      throws InstantiationException, IllegalAccessException {
      Box<String> stringBox = new Box<String>();
      add(stringBox, String.class);
   }  

   pubpc static <T> void add(Box<T> box) {
      //compiler error
      //Cannot instantiate the type T
      //T item = new T();  
      //box.add(item);
   }

   pubpc 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;

   pubpc void add(T t) {
      this.t = t;
   }

   pubpc T get() {
      return t;
   }   
}

This will produce the following result −

Item added.
Advertisements