[英]Why cast to Closeable first?
While reading some Java source, I came across this line: 在阅读一些Java源代码时,我遇到了这一行:
((Closeable) some_obj).close();
some_obj is obviously an instance of a class which implements the Closeable interface. some_obj显然是实现Closeable接口的类的实例。 My question is, why do they first cast some_obj to Closeable before invoking close(). 我的问题是,为什么他们在调用close()之前首先将some_obj强制转换为Closeable。 Couldn't I just do 我不能这样做
some_obj.close();
Assuming the compile-time type of some_obj
implements Closeable
, then yes, you could. 假设some_obj
的编译时类型实现了Closeable
,那么是的,你可以。
You'd only need this if you had an object which you knew implemented Closeable
, but where the compile-time type was something more general (the most obvious example being Object
) or otherwise "different" (eg a different interface). 如果你有一个你知道实现的对象是Closeable
,但是编译时类型更通用(最明显的例子是Object
)或者“不同”(例如不同的接口), 你只需要这个。
Just as a matter of interest, in C# a cast to an interface type can make a difference, even if the compile-time type is known to implement the interface, due to explicit interface implementation. 正如感兴趣的事情,在C#强制转换为一个接口类型可以有所作为,即使编译时类型是已知的实现接口,由于显式接口实现。 I can give more details if anyone cares, but I just thought I'd throw it out there. 如果有人关心,我可以提供更多细节,但我只是想把它扔出去。
如果变量some_obj
的已知编译时类型包含方法close()
, some_obj
yes。
It sounds like typecast is unnecessary. 这听起来像是没有必要进行类型转换。 (You could confirm this by trying to compile the class with the supposedly redundant typecast removed.) (您可以通过尝试编译具有所谓的冗余类型转换的类来确认这一点。)
We may never know why the code was written that way. 我们可能永远不知道为什么代码是这样编写的。 It might be left over from a previous incarnation of the code where the declared type of some_obj
was different. 它可能会遗留在代码的前一个版本中,其中声明的some_obj
类型不同。 It might be that the developer had some stylistic issues ... 可能是开发人员有一些风格问题......
While it would (probably) the code's improve readability if the redundant cast was removed, it is not actually doing any harm. 虽然如果删除了多余的强制转换,它(可能)代码会提高可读性,但它实际上并没有造成任何伤害。 I expect that the Java compiler or the JIT compiler will optimize it away. 我希望Java编译器或JIT编译器能够优化它。 And even if it doesn't, the cost of a redundant typecast is most likely insignificant. 即使它没有,多余的类型转换的成本很可能是微不足道的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.