繁体   English   中英

Java泛型方法类型转换

[英]Java generic method type casting

为什么会这样? 代码中的一行运行良好,而另一条相似的代码则没有。 自动类型转换是否仅在某些条件下发生? 我试图将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;
    }
}

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不知道泛型方法将在编译时返回什么类,因此classTypeException

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

你应该首先将它分配给一个变量,因为jvm在编译时知道变量的类型

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

为了消除错误。

编译器使用Generic来检查期望的对象类型,因此它可以捕获开发人员在编译时所犯的错误(与运行时错误相比)。 所以恕我直言这种使用泛型的方式击败了目的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM