我知道 java 不应该支持作为原始类型的泛型参数,并且确实是这样的:
Vector<byte> test;
将无法编译。
但是,我在程序中不小心执行了一些操作,我发现实际上可以创建具有原始类型的通用对象(技术如下所示)
Vector<Byte>
此外,当打印语句显示 byte.class 和 Byte.class 是两个独立的野兽时,java 错误地允许将此实例分配给类型变量。因此,尝试对对象进行调用会导致意外和奇怪的行为/错误。
这是一个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);
}
}