OnJava8-Examples/generics/InstantiateGenericType.java

35 lines
852 B
Java
Raw Normal View History

2015-04-20 15:36:01 -07:00
//: generics/InstantiateGenericType.java
2015-05-29 14:18:51 -07:00
// <20>2015 MindView LLC: see Copyright.txt
2015-04-20 15:36:01 -07:00
import static net.mindview.util.Print.*;
class ClassAsFactory<T> {
T x;
public ClassAsFactory(Class<T> kind) {
try {
x = kind.newInstance();
2015-05-06 12:09:38 -07:00
} catch(InstantiationException |
IllegalAccessException e) {
2015-04-20 15:36:01 -07:00
throw new RuntimeException(e);
}
}
}
2015-05-18 23:05:20 -07:00
class Employee {}
2015-04-20 15:36:01 -07:00
public class InstantiateGenericType {
public static void main(String[] args) {
ClassAsFactory<Employee> fe =
2015-05-05 11:20:13 -07:00
new ClassAsFactory<>(Employee.class);
2015-04-20 15:36:01 -07:00
print("ClassAsFactory<Employee> succeeded");
try {
ClassAsFactory<Integer> fi =
2015-05-05 11:20:13 -07:00
new ClassAsFactory<>(Integer.class);
2015-04-20 15:36:01 -07:00
} catch(Exception e) {
print("ClassAsFactory<Integer> failed");
}
}
} /* Output:
ClassAsFactory<Employee> succeeded
ClassAsFactory<Integer> failed
*///:~