java 范型问题求解答

都说java 不支持创建范型数组的原因是因为防止编译通过但是可能在运行过程中出现classcastexception的情况

GenTest<String> genArr[] = new GenTest<String>[2];
Object[] test = genArr;
GenTest<StringBuffer> strBuf = new GenTest<StringBuffer>();
strBuf.setValue(new StringBuffer());
test[0] = strBuf;
GenTest<String> ref = genArr[0]; //上面两行相当于使用数组移花接木,让Java编译器把GenTest<StringBuffer>当作了GenTest<String>
String value = ref.getValue();// 这里是重点!

 但是其实即使不用数组 一样也可能出现运行中classcastexception的情况

public class Test<t> {
   private t value;

   public static void main(string args[]) {
      test<string> t = new test<string>();
      t.setvalue("abc");
      object o = t;
      test<stringbuffer> b = (test<stringbuffer>)o;
      system.out.println(b.getvalue().append("abcd");
   }
   
   public t getvalue() {
      return value;
   }

   public void setvalue(t value) {
      this.value = value;
   }

 

强制转型编译器肯定检查不多,只能在运行期抛出ClassCastException了。这个强制转型貌似跟泛型不能混为一谈吧

java的泛型会在编译成bytecode的时候擦除掉的...不会留到运行时的