在我学习 C + + 的日子里,我学到了 C 风格的强制转换操作符的弊端,起初我很高兴地发现,在 Java 5中,java.lang.Class
已经获得了一个 cast
方法。
我以为我们终于有了一个 OO 的方式来处理选角。
Turns out Class.cast
is not the same as static_cast
in C++. It is more like reinterpret_cast
. It will not generate a compilation error where it is expected and instead will defer to runtime. Here is a simple test case to demonstrate different behaviors.
package test;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class TestCast
{
static final class Foo
{
}
static class Bar
{
}
static final class BarSubclass
extends Bar
{
}
@Test
public void test ( )
{
final Foo foo = new Foo( );
final Bar bar = new Bar( );
final BarSubclass bar_subclass = new BarSubclass( );
{
final Bar bar_ref = bar;
}
{
// Compilation error
final Bar bar_ref = foo;
}
{
// Compilation error
final Bar bar_ref = (Bar) foo;
}
try
{
// !!! Compiles fine, runtime exception
Bar.class.cast( foo );
}
catch ( final ClassCastException ex )
{
assertTrue( true );
}
{
final Bar bar_ref = bar_subclass;
}
try
{
// Compiles fine, runtime exception, equivalent of C++ dynamic_cast
final BarSubclass bar_subclass_ref = (BarSubclass) bar;
}
catch ( final ClassCastException ex )
{
assertTrue( true );
}
}
}
这就是我的问题。
Class.cast()
应该被放逐到泛型的土地吗? 在那里它有相当多的合法用途。Class.cast()
时,编译器是否应该生成编译错误,并且在编译时可以确定非法条件?