Java raw type value assigned to generic type run time getClss() method error -


public class box<t> {     private t t;     public box(t t){         this.t = t;     }     public void add(t t) {       this.t = t;     }     public t get() {       return t;     }     public static void main(string[] args) {       box<integer> b = new box(new string("may be"));       system.out.println(b.get()); // print out "may be"       system.out.println(b.get().getclass()); // error    } } 

this code gives runtime error:

exception in thread "main" java.lang.classcastexception: java.lang.string cannot cast java.lang.integer 
  1. why b.get() not triggering runtime error?
  2. why runtime error occur when try class of class variable?

to more precise: why compiler inserting checkcast instruction bytecode only second get() (leading exception)?

please note:

  • in first case, result of get() used println(object): in other words: receiving side expects object, , "condition" true.
  • in second case, method invocation on returned object follow. , makes can make huge difference if returned type expected one. therefore compiler adding check guarantee following method call sound.

as background, 1 can java language specification, chapter 5.52:

the cast checked cast.

such cast requires run-time validity check. if value @ run time null, cast allowed. otherwise, let r class of object referred run-time reference value, , let t erasure (§4.6) of type named in cast operator. cast conversion must check, @ run time, class r assignment compatible type t, via algorithm in §5.5.3.

respectively chapter 5.53 checked casts @ run time.


Comments

Popular posts from this blog

Is there a better way to structure post methods in Class Based Views -

performance - Why is XCHG reg, reg a 3 micro-op instruction on modern Intel architectures? -

jquery - Responsive Navbar with Sub Navbar -