将已知类型的引用转换为类型层次结构之外的接口 [英] Cast reference of known type to an interface outside of type's hierarchy

查看:88
本文介绍了将已知类型的引用转换为类型层次结构之外的接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设你有一个干净的类:

Say you have a clean class like this:

public class A {
    // Stuff
}

接口如下:

public interface G {
    // Stuff
}


b $ b

为什么我允许这样做:

Why am I allowed to do this:

A a = new A();
((G) a) // No errors thrown

当它们与彼此无关时,应该可以从类A转换到接口G.有人可以向我解释这个吗?

I can't understand why it should be possible to cast from the class A to the interface G when they have nothing to do with each other. Can someone please explain this to me?

后续行动。如果我做以下:

Follow-up. If I make the following:

public class C implements G {
    // Stuff
}

这将无法编译:

((C) a)

实现接口和接口?

编辑:我得到一个编译器错误说:

I get a compiler-error saying:


无法从A到C转换

Cannot cast from A to C


推荐答案

编译器什么是有效的。你告诉编译器关闭并跟随你的领导。编译器可以在少数情况下告诉一个转换是无效的,但很容易欺骗。

Casting means you know better than the compiler what's valid. You are telling the compiler to shut up and follow your lead. The compiler can tell in a few cases that a cast is invalid, but it is easy to fool.

大多数转换往往是从对象到其他,如从非泛型集合中获取对象或使用PortableRemoteObject.narrow获取远程对象时。这些转换总是编译,因为无论你转换为什么(只要它是一个对象,而不是一个原始)总是一个有效的对象的子类。

Most casts tend to be from Object to something else, such as in getting an object out of a non-genericized collection or when getting a remote object using PortableRemoteObject.narrow. These casts always compile because whatever you cast to (as long as it's an Object, and not a primitive) is always a valid subclass of Object.

有一些规则在Java语言规范中的引用类型铸件(5.5.1)。如果编译器可以弄清楚类之间没有关系(编译器可以告诉类是不同的,也不是另一个的子类),那么它将拒绝转换。

There are some rules for casting in the Java language specification in the section Reference Type casting (5.5.1). If the compiler can figure out there is no relationship between the classes (the compiler can tell the classes are different and neither is a subclass of the other) then it will reject the cast.

添加的示例很有趣,它失败,因为编译器有足够的信息来判断转换是无效的。如果您将代码更改为:

The added example is interesting, it fails because the compiler has enough information to tell that the cast is invalid. If you change the code to:

    A a = new A();
    G g = (G)a;
    Object o = a;
    C c = (C)o;

然后它再次编译正常(即使它是错误的)。

then it compiles fine again (even though it is just as erroneous).

这篇关于将已知类型的引用转换为类型层次结构之外的接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆