心法领悟185:Java泛型的局限。
Java泛型使用起来有很多的局限性,如不能使用基本类型作为其类型参数、不能抛出或捕获泛型类型的实例、不能直接使用泛型数组、不能实例化类型变量等。希望读者在使用泛型时多加注意。对于其中的某些不足,可以使用Java的反射机制进行弥补。虽然反射的效率不高,但是也只能忍受了。
package com.mingrisoft.generic;
import java.lang.reflect.Array;
public class GenericArray<T> {
private T[] array;
private int size;
@SuppressWarnings("unchecked")
public GenericArray(Class<T> type, int size) {
this.size = size;
array = (T[]) Array.newInstance(type, size);
}
public void put(int index, T item) {
if (size > index) {
array[index] = item;
}
}
public T get(int index) {
if (size > index) {
return array[index];
} else {
return null;
}
}
}
package com.mingrisoft.generic;
public class GenericArrayTest {
public static void main(String[] args) {
System.out.println("创建String类型的数组并向其添加元素:明日科技");
GenericArray<String> stringArray = new GenericArray<String>(String.class, 10);
stringArray.put(0, "明日科技");
System.out.println("String类型的数组元素:" + stringArray.get(0));
System.out.println("创建Integer类型的数组并向其添加元素:123456789");
GenericArray<Integer> integerArray = new GenericArray<Integer>(Integer.class, 10);
integerArray.put(0, 123456789);
System.out.println("Integer类型的数组元素:" + integerArray.get(0));
}
}
运行结果:
创建String类型的数组并向其添加元素:明日科技
String类型的数组元素:明日科技
创建Integer类型的数组并向其添加元素:123456789
Integer类型的数组元素:123456789
补充阅读:
java.lang.Class<T>
Instances of the class Class represent classes and interfaces in a running Java application. An enum is a kind of class and an annotation is a kind of interface. Every array also belongs to a class that is reflected as a Class object that is shared by all arrays with the same element type and number of dimensions. The primitive Java types (boolean, byte, char, short, int, long, float, and double), and the keyword void are also represented as Class objects.
Class has no public constructor. Instead Class objects are constructed automatically by the Java Virtual Machine as classes are loaded and by calls to the defineClass method in the class loader.
The following example uses a Class object to print the class name of an object:
void printClassName(Object obj) {
System.out.println("The class of " + obj +
" is " + obj.getClass().getName());
}
It is also possible to get the Class object for a named type (or for void) using a class literal. See Section 15.8.2 of The Java™ Language Specification. For example:
System.out.println("The name of class Foo is: "+Foo.class.getName());
Parameters:
<T> the type of the class modeled by this Class object. For example, the type of String.class is Class<String>. Use Class<?> if the class being modeled is unknown.
Since:
JDK1.0
Author:
unascribed
See Also:
java.lang.ClassLoader.defineClass(byte[], int, int)