简体   繁体   English

为什么对对象类型转换通用的是隐式的?

[英]Why generic to object type-casting is implicit?

While converting an non-generic class to a generic one, I saw this working : 在将非泛型类转换为泛型类时,我看到了这一工作:

public class TestException<T>
{
    T t;
    Object getObj(){
        return t;   
    }
}

When I tried to change the return-type from Object to any other say String , I had to type cast it : 当我尝试将return类型从Object更改为任何其他String ,我必须键入cast:

String getObj(){
    return (String)t;   
}

Why generic to object type-casting is implicit ? 为什么通用的对象类型转换是隐式的? Couldn't find any implementation on java docs. 在Java文档上找不到任何实现。

每个类都继承Object ,因此T保证可以隐式转换为Object

Since your generic type T is unbound, it gets the implicit bound T extends Object . 由于您的通用类型T是未绑定的,因此它获得隐式绑定T extends Object This means that it's fine for it to be returned as an Object . 这意味着可以将它作为Object返回。

There's no guarantee that T is a String , so you're forced to cast it (and you run the risk of runtime exceptions if you do and T is not a String ). 不能保证TString ,所以您必须强制将其强制转换(如果这样做并且T不是String则存在运行时异常的风险)。

even if T wasn't generics type it would have worked. 即使T不是泛型类型,它也可以工作。 try it yourself! 自己尝试!

you can always return something as it super type, same goes for generics 您总是可以返回一些超级类型的东西,泛型也一样

Every instance of every class ISA Object, so you can always cast any reference type value to Object. 每个类ISA Object的每个实例,因此您始终可以将任何引用类型值转换为Object。 Only a String object, however, ISA String. 但是只有一个String对象,ISA String。

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

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