Java泛型方法类型转换



为什么会发生这种情况?代码中的一行运行良好,而另一行类似的代码则不正常。自动类型铸造是否只在特定条件下发生?我曾尝试将gt.echoV()分配给一个Object,它运行良好;但是当我把它分配给一个字符串时,同样的错误会再次出现。

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;
    }
}

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();

泛型"免费"得到的是(String)类型转换。没有别的。

这是完美的,没有什么特别的,普通使用泛型

gt.<String>echoV(); //this line works well

这里有一些不太明显的东西。因为泛型方法是在运行时定义的,jvm不知道泛型方法在compiletime将返回什么类型的Class吗,因此classTypeException

gt.<String>echoV().getClass();//this line leads to a type cast exception   

您应该先将它分配给一个变量,因为jvm确实知道compiletime中变量的类型

String s = gt.<String>echoV();
s.getClass();

更改此行:

gt.<String>echoV().getClass();

至:

(gt.echoV()).getClass();

它将编译
(它将返回:类java.lang.Object

ClassCastException的根是该方法返回t(属于泛型类型T,它是一个对象),并尝试将其向下转换为String。您也可以更改代码以返回:

return (T)"some-string";

以便消除错误。

泛型由编译器用来检查期望的对象类型,因此它可以捕捉开发人员在编译时犯下的错误(与运行时错误相比)。所以IMHO这种使用泛型的方式违背了目的。

最新更新