-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathInstantiateGenericType.java
More file actions
48 lines (37 loc) · 1.08 KB
/
InstantiateGenericType.java
File metadata and controls
48 lines (37 loc) · 1.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package generics;
import java.util.*;
/**
* RUN:
* javac generics/InstantiateGenericType.java && java generics.InstantiateGenericType
* OUTPUT:
* ClassAsFactory<Employee> success!
* ClassAsFactory<Integer> failure!
*/
// COMPILETIME ERROR !!!
public class InstantiateGenericType {
public static void main(String[] args) {
ClassAsFactory<Employee> fe = new ClassAsFactory<Employee>(Employee.class);
System.out.println("ClassAsFactory<Employee> success!");
try {
//
// Fire exception here cause Integer class have not constructor w/o args !
//
ClassAsFactory<Integer> fi = new ClassAsFactory<Integer>(Integer.class);
}
catch(Exception e) {
System.out.println("ClassAsFactory<Integer> failure!");
}
}
}
class ClassAsFactory<T> {
T x;
public ClassAsFactory(Class<T> kind) {
try {
x = kind.newInstance();
}
catch(Exception e) {
throw new RuntimeException(e);
}
}
}
class Employee {}