OnJava8-Examples/generics/ArrayMaker.java

22 lines
594 B
Java
Raw Normal View History

2015-09-07 11:44:36 -06:00
// generics/ArrayMaker.java
2015-06-15 17:47:35 -07:00
import java.lang.reflect.*;
import java.util.*;
public class ArrayMaker<T> {
private Class<T> kind;
public ArrayMaker(Class<T> kind) { this.kind = kind; }
@SuppressWarnings("unchecked")
T[] create(int size) {
return (T[])Array.newInstance(kind, size);
}
public static void main(String[] args) {
ArrayMaker<String> stringMaker =
new ArrayMaker<>(String.class);
String[] stringArray = stringMaker.create(9);
System.out.println(Arrays.toString(stringArray));
}
2015-09-07 11:44:36 -06:00
}
/* Output:
2015-06-15 17:47:35 -07:00
[null, null, null, null, null, null, null, null, null]
2015-09-07 11:44:36 -06:00
*/