Imagine we have the following generic class:
public class GenericClass<U> {
private U value;
public GenericClass(U value) {
this.value = value;
}
}
and the following generic method in some other class MyClass:
public <T extends BT, BT> void genericMethod(T arg) {
Object genericClass = new GenericClass<BT>(arg);
}
Which value will BT type parameter obtain if we call
genericMethod("text");
?
Some notes:
The above code compiles without errors or warnings, which seems strange for me. Decompiling (by means of IntelliJ IDEA 2016) shows the following code:
public <T extends BT, BT> void genericMethod(T arg) {
new MyClass.GenericClass(arg);
}
Notice that new GenericClass<BT>(arg)
is not the same as new GenericClass(arg)
because the latter is equivalent of new GenericClass<T>(arg)
(type deduction), and although T extends BT
, these are different types, and GenericClass
may have internal logic where the exact type name plays an important role (e.g. is used as a string key in some map etc). So for me it is strange why the compiler silently uses type deduction instead of producing some warning (or maybe even error) stating that BT type parameter is not specified. Maybe I'm missing smth. important about generics in Java, however...