Java 允许在泛型中使用基元类型
我知道java不应该支持基元类型的泛型参数,果然是这样的:
Vector<byte> test;
将无法编译。
但是,通过我在程序中意外执行的一点点手,我发现实际上可以创建具有基元类型的通用对象(如下所示的技术)
此外,java错误地允许将此实例分配给类型的变量,而正如print语句所示,byte.class和byte.class是两个独立的野兽。因此,尝试对对象进行调用会导致意外和奇怪的行为/错误。Vector<Byte>
这是一个java错误吗?还是这种疯狂有什么押韵或理由?似乎即使java允许创建基元类型泛型的意外行为,它们也不应该被分配给包装器类型的泛型,该泛型与原语的类不同。
import java.util.Vector;
public class Test
{
//the trick here is that I am basing the return type of
//the vector off of the type that was given as the generic
//argument for the instance of the reflections type Class,
//however the the class given by byte.class yields a non-class
//type in the generic, and hence a Vector is created with a
//primitive type
public static <Type> Vector<Type> createTypedVector(Class<Type> type)
{
return new Vector<Type>(0,1);
}
public static void main(String ... args)
{
//these lines are to demonstrate that 'byte' and 'Byte'
//are 2 different class types
System.out.println(byte.class);
System.out.println(Byte.class);
//this is where I create an instance of type Vector<byte>
//and assign it to a variable of type Vector<Byte>
Vector<Byte> primitiveTypedGenericObject = createTypedVector(byte.class);
//this line causes unexpected exceptions to be thrown
//because primitiveTypedGenericObject is not actually type
//Vector<Byte>, but rather Vector<byte>
primitiveTypedGenericObject.set(0,(byte)0xFF);
}
}