Java Type Erasure: Rules of cast insertion?

前端 未结 2 367
一生所求
一生所求 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.

    0 讨论(0)
  • 2020-12-22 10:03
    1. MyNode mn = new MyNode(5);

      • will create an instance of MyNode which defines the generic type T of interface Node as Integer
      • casting: no casting necessary by developer, no casts added by compiler
    2. Node n = (MyNode)mn;

      • this will basically tell the compiler forget about the generic type T and use the interface Node completely without generics which will have the following consequence: imagine generic type T to be treated as java.lang.Object
      • casting: no casting necessary by developer, no casts added by compiler
    3. n.setData("Hello");

      • will allow you to add any kind ob object because T is treated as Object (String, Integer, array, anything else)
      • casting: no casting necessary by developer, no casts added by compiler
    4. Integer x = mn.data;

      • nm.data should return an Integer type as Integer is defined as generic type argument T in the MyNode class
      • however because you used raw types which allowed you to add a String instead, the nm.data holds a String instance
      • casting: no casting necessary by developer, however the compiler will add casts to Integer behind the scenes for you and because of type mismatch, you will get the ClassCastException
    0 讨论(0)
提交回复
热议问题