我正在遍历
如果运行代码的这一部分,我会收到以下错误:
然而,在另一个地方,我有一个返回
ArrayList<Bar>
。 Foo
扩展了 Bar
。 我尝试在列表中找到 Foo
的一个实例。ArrayList<Bar> list = new ArrayList<Bar>();
// fill list with items that are instances of Foo and Bar
for (int i = 0; i < list.size(); i++)
{
Bar bar = list.get(i);
if (bar.getClass().getName().equals("com.me.Foo")) // "if(bar instanceof Foo)" never passes
{
System.out.println("bar is an instance of Foo");
Foo foo = (Foo) bar;
}
}
如果运行代码的这一部分,我会收到以下错误:
java.lang.ClassCastException: com.me.Foo cannot be cast to com.me.Foo
// stack
然而,在另一个地方,我有一个返回
Bar
实例的方法,我可以使用instanceof
检查它是否是Foo
实例,然后毫无问题地将Bar
转换为Foo
。Bar bar = returnBar(); // returns an instance of Bar, but the variable
// it returns could be an instance of Foo
if (bar instanceof Foo)
{
System.out.println("bar is an instance of Foo");
Foo foo = (Foo) bar;
}
这里有什么不同?
这是问题的真正来源: http://pastie.org/private/jhyhovn7mm4ghxlxsmweog
我正在使用一个名为Bukkit的API,它允许为名为Minecraft的游戏的服务器创建自定义插件。文档可以在这里找到,对于那些真正感兴趣的人来说,这个问题已经变成了API特定的问题,我将去官方的Bukkit论坛尝试我的问题,但我会把所有这些留在这里,以供那些对问题感兴趣的人参考。
ArrayList
中的变量和returnBar()
收到的变量,还是类。答案是肯定的。 - Austin Moore