as far as I know, java
virtual machines don"t recognize generic classes or generic methods, so when compiled into bytecode, all generic classes or generic methods are converted to normal classes or methods.
for example:
//
class Test<T> {
public T res = null;
public Test(T res){
this.res = res;
}
public T get(){
return this.res;
}
}
Test t = new Test<String>("-Test-get");
//
String res = t.get();
Type parameters are replaced at compile time (type erasure), that is, the code in the compiled bytecode should be as follows:
public class Test {
private String res = null;
public Test(String res){
this.res = res;
}
public String get(){
return this.res;
}
}
Test t = new Test("-Test-get");
// :Object ?
String t = t.get();
the problem lies in:
Test t = new Test<String>();
// Object
String res = t.get();
I am very depressed. cannot understand why a method call after providing a type parameter returns not the supplied type String
but the Object
type?
however, in the following scenario, the result is correct
//
Test<String> t = new Test<>();
String res = t.get();
Why is this?