Java determines which method to call using a generic type argument?
To my knowledge, Java drops the generic type argument information during
runtime. It is only used on compilation to perform checks, for example, is
this particular method call valid or not.
Today I came across the following piece of code, in which, seemingly, Java
determines by the collection/list type argument, which constructor to
call:
public static class MyClass {
public MyClass(final Collection<String> coll) {
System.out.println("Constructor 1");
}
public MyClass(final List<Integer> list) {
System.out.println("Constructor 2");
}
}
The following calls are made:
new MyClass(new HashSet<String>()); // Constructor 1
new MyClass(new ArrayList<String>()); // Constructor 1
new MyClass(new ArrayList<Integer>()); // Constructor 2
Now, if I erase the type arguments:
public static class MyClass2 {
public MyClass2(final Collection coll) {
System.out.println("Constructor 1");
}
public MyClass2(final List list) {
System.out.println("Constructor 2");
}
}
...The same calls act as I would expect them to; constructor invocation
which uses a list argument goes for the constructor which meets its needs
"most precisely":
new MyClass2(new HashSet<String>()); // Constructor 1
new MyClass2(new ArrayList<String>()); // Constructor 2
new MyClass2(new ArrayList<Integer>()); // Constructor 2
It appears that generics information is being stored in the compiled class
(in this case, MyClass) and is not being discarded after all, but it
should be discarded. What am I misunderstanding?
No comments:
Post a Comment