Java泛型方法类型转换

cha*_*_ma 6 java generics

为什么会这样?代码中的一行运行良好,而另一条相似的代码则没有.自动类型转换是否仅在某些条件下发生?我试图将gt.echoV()分配给一个对象,它运行良好; 但是当我将它分配给一个String时,同样的错误将再次出现.

public class GeneMethodTest {

    public static void main(String... args) {
        GeneMethodTest gt = new GeneMethodTest();
        gt.<String>echoV(); //this line works well
        gt.<String>echoV().getClass();//this line leads to a type cast exception                                                          
    }

    public <T> T echoV() {
        T t=(T)(new Object());                                                                    
        return t;
    }
}
Run Code Online (Sandbox Code Playgroud)

Hot*_*cks 4

gt.<String>echoV().getClass();产生与以下操作序列等效的结果:

// Inside echoV
Object t = new Object();  // Note that this is NOT a String!
Object returnValue = t;
// In main
String stackTemp = (String) returnValue;  // This is the operation that fails
stackTemp.getClass();
Run Code Online (Sandbox Code Playgroud)

您通过泛型“免费”获得的就是(String)演员阵容。没有其他的。