Java Type Erasure: Rules of cast insertion?

前端 未结 2 394
一生所求
一生所求 2020-12-22 09:16

The Java tutorial on type erasure doesn\'t seem to detail the specific rules of cast insertion by the compiler. Can someone please explain the specific rules that cause the

2条回答
  •  忘掉有多难
    2020-12-22 09:50

    The ClassCastException would be throw when a call is made to

    n.setData("Hello");
    

    This is because the compiler builds bridge methods to preserve polymorphism. The bridge method will look like:

     public void setData(Object data) {
           setData((Integer)data);   //the exception is thrown here
      }
    

    since an instance of a string cannot be converted to Integer, the ClassCastException would be thrown.

    You can read about bridge methods here.

提交回复
热议问题