Java type erasure - why can I see the type when I look at the bytecode? -


i trying understand why writing both methods in class not allowed

 public bool plus(list<string>) {return true;}  public bool plus(list<integer>) {return true;} 

i try figure how related type erasure when decompile following code

public class test<t> {     boolean plus2(list<t> ss) {return false;}    boolean plus(list<string> ss) {return false;}    boolean plus(set<integer> ss) {return false;} } 

i same when decompile java decompiler (jd)

even when print byte code can see types.
(looking @ answer declares 'but rest assure types erased in bytecode' )

    compiled "test.java"     public class com.example.test<t> {     public com.example.test();             code:             0: aload_0             1: invokespecial #1                  // method java/lang/object."<init>":()v             4: return              boolean plus2(java.util.list<t>);             code:             0: iconst_0             1: ireturn              boolean plus(java.util.list<java.lang.string>);             code:             0: iconst_0             1: ireturn              boolean plus(java.util.set<java.lang.integer>);             code:             0: iconst_0             1: ireturn             } 

your compiler needs able check generic type information based on information in byte code.

java 5.0+ records generic information in byte code, doesn't record in object instance.

e.g. there no way generic type of list

 // list.getclass() arraylist doesn't record generic type. list list = new arraylist<string>(); 

however does

// list.getclass() not arraylist // list instance of class extends arraylist<string> list list = new arraylist<string>() { };  parameterizedtype t = (parameterizedtype) list.getclass().getgenericsuperclass(); assert t.getrawtype() == arraylist.class; assert t.getactualtypearguments()[0] == string.class; 

this because byte code of sub-class of arraylist records generic used in it's parent.

note: works fields, constructor/method arguments return types , actual type recorded in byte code.

however, none of these mean generic type of instance available (though generic type of parent class/interface available if recorded in byte code.


Comments

Popular posts from this blog

java - Run spring boot application error: Cannot instantiate interface org.springframework.context.ApplicationListener -

reactjs - React router and this.props.children - how to pass state to this.props.children -

Excel VBA "Microsoft Windows Common Controls 6.0 (SP6)" Location Changes -