Java why method overload from generic type cannot be determined at compile time -
i wondering why following code cannot use compile-time generic type information correctly lookup specific method overload, instead uses method applicable potential generic parameters. there no way of switching on generic parameter type @ compile time avoid nasty reflection @ runtime?
import org.junit.assert; import org.junit.test; import java.util.arraylist; import java.util.list; public class temp { class a<t> { t x; a(t x) { this.x = x; } string bar = foo(x); private string foo(integer i) { return "int"; } private string foo(string i) { return "string"; } private <t> string foo(list<t> l) { return "list"; } private <t> string foo(t v) { return "value"; } } @test public void inttest() { assert.assertequals(new a<integer>(1).bar, "int"); } @test public void stringtest() { assert.assertequals(new a<string>("a").bar, "string"); } @test public void listtest() { assert.assertequals(new a<list<string>>(new arraylist<string>()).bar, "list"); } @test public void longtest() { assert.assertequals(new a<long>(1l).bar, "value"); } }
this because compiler have generate different class a
each type used t
(because initializer a.bar
need call different method). decision made generate 1 class. different e.g. c++ compiler generates new type used type parameters.
in other words compiled code type a<string>
different type a<integer>
, after compilation there type a
.
Comments
Post a Comment