i totally understand erasure of generic , therefore java cant overloading base on generic. if take lambda expression consideration?
see following case.
interface base{ void test(); } // compiler cant distinguish these 2 interfaces lambda expression provided interface foo extends base{} interface boo extends base{} public static void main(string[] args) throws classnotfoundexception { hashmap<string,long> set = new hashmap<>(); // valid, since type foo explicitly given out t1(set,new foo(){ @override public void test(){ } }); // "long" // using lambda expression make second argument indistinguishable, //so overloading can depend on first argument //hashmap generic type. // compiler still managed work out t1(set,()->{});// "long" hashmap<string,integer> set2 = new hashmap<>(); t1(set2,()->{});// "integer" } public static void t1(hashmap<string,long> set,foo foo){system.out.println("long");} public static void t1(hashmap<string,integer> set,boo boo){system.out.println("integer");}
the result of each function call expected without compile or runtime error. , that's weired part of whole thing: function overloading based on generic types.
so going on behind scenes?
interesting question.
the compiler decides @ compile time type lambda function is, though generics wiped away @ point, type of function set @ point, meaning knows method has called.
my guess can because still has generic information @ stage -- i.e. compiler gets rid of it.
if @ bytecode class says:
16: invokestatic #25 // method t1: (ljava/util/hashmap;ltest$foo;)v 25: invokestatic #25 // method t1: (ljava/util/hashmap;ltest$foo;)v
so hashmap typing gone, interface, type has been set.
Comments
Post a Comment