// generics/InstantiateGenericType.java // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.function.*; class ClassAsFactory implements Supplier { Class kind; public ClassAsFactory(Class kind) { this.kind = kind; } @Override public T get() { try { return kind.newInstance(); } catch(InstantiationException | IllegalAccessException e) { throw new RuntimeException(e); } } } class Employee { @Override public String toString() { return "Employee"; } } public class InstantiateGenericType { public static void main(String[] args) { ClassAsFactory fe = new ClassAsFactory<>(Employee.class); System.out.println(fe.get()); ClassAsFactory fi = new ClassAsFactory<>(Integer.class); try { System.out.println(fi.get()); } catch(Exception e) { System.out.println(e.getMessage()); } } } /* Output: Employee java.lang.InstantiationException: java.lang.Integer */