iteye_15708 2013-11-27 11:10
浏览 192
已采纳

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;
   }
  • 写回答

2条回答 默认 最新

  • iteye_14005 2013-11-27 12:21
    关注

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?