私は、Javaがプリミティブ型であるジェネリック引数をサポートしていないことを知っています。確かに、次のようなものです。
Vector<byte> test;
コンパイルに失敗します。
しかし、私がプログラムで誤って実行したちょっとした操作で、プリミティブ型の汎用オブジェクトを実際に作成できることがわかりました (以下に示す手法)。
Vector<Byte>
さらに、javaは、print ステートメントが示すように、byte.class と Byte.class が 2 つの別個の獣である場合に、このインスタンスをタイプの変数に割り当てることを誤って許可します。このため、オブジェクトに対して呼び出しを実行しようとすると、予期しない奇妙な動作/エラーが発生します。
これは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);
}
}