OnJava8-Examples/generics/InstantiateGenericType.java
2016-01-25 18:05:55 -08:00

46 lines
1.1 KiB
Java

// generics/InstantiateGenericType.java
// (c)2016 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
import java.util.function.*;
class ClassAsFactory<T> implements Supplier<T> {
Class<T> kind;
public ClassAsFactory(Class<T> 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<Employee> fe =
new ClassAsFactory<>(Employee.class);
System.out.println(fe.get());
ClassAsFactory<Integer> 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
*/