Java 转换接口到类 [英] Java Casting Interface to Class
问题描述
public class InterfaceCasting {
private static class A{}
public static void main(String[] args) {
A a = new A();
Serializable serializable = new Serializable(){};
a = (A)serializable;
}
}
编译成功但运行时异常
Exception in thread "main" java.lang.ClassCastException: InterfaceCasting$1 cannot be cast to InterfaceCasting$A
为什么编译成功?编译器一定知道serialiazable不是A?
WHY COMPILATION SUCCEED? Compiler must known that serialiazable is not A?
推荐答案
正如你所指出的,这将编译:
As you point out, this will compile:
interface MyInterface {}
class A {}
public class InterfaceCasting {
public static void main(String[] args) {
MyInterface myObject = new MyInterface() {};
A a = (A) myObject;
}
}
这个但是,不会编译:
interface MyInterface {}
class A {}
public class InterfaceCasting {
public static void main(String[] args) {
A a = (A) new MyInterface() {}; // javac says: "inconvertible types!"
}
}
那么,这里发生了什么?有什么区别?
So, what's going on here? What's the difference?
好吧,由于 MyInterface
只是一个接口,它可以很好地由扩展 A 的类实现,在这种情况下从 MyInterface
转换为 A
是合法的.
Well, since MyInterface
is simply an interface, it could very well be implemented by a class that extends A, in which case the cast from MyInterface
to A
would be legal.
例如,这段代码将在所有执行的 50% 中成功,并说明编译器需要解决可能无法确定的问题,以便始终在编译时检测"非法强制转换.
This code for instance, will succeed in 50% of all executions, and illustrates that the compiler would need to solve possibly undecidable problems in order to always "detect" illegal casts at compile time.
interface MyInterface {}
class A {}
class B extends A implements MyInterface {}
public class InterfaceCasting {
public static void main(String[] args) {
MyInterface myObject = new MyInterface() {};
if (java.lang.Math.random() > 0.5)
myObject = new B();
A a = (A) myObject;
}
}
这篇关于Java 转换接口到类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!