EntitySpriteMonster instanceof Entity... that simple and it doesnt work?
I have code like:
class Entity;
class EntityTool extends Entity;
class EntitySprite extends Entity;
class EntityToolSpoon extends EntityTool;
class EntityToolBow extends EntityTool;
class EntitySpritePlayer extends EntitySprite;
class EntitySpriteMonster extends EntitySprite;
Now I have a method called move()
in Entity
, and some others overwrite it.
Now, if the argument is an EntitySpriteMonster
, why does t开发者_开发技巧his not work:
public void foonction(Object wut)
{
if (wut instanceof Entity) ((Entity)wut).move(x,y);
}
The move function (though this is redundant and unneeded. it fails at if rawpeek instanceof...
):
@Override
public void move(double x, double y) {
super.move(x, y);
for (int i=0; i<8; i++) {
Object rawpeek = palette.get(i);
System.out.println(rawpeek);
if (rawpeek == null) continue;
if (rawpeek instanceof Entity)
((Entity) rawpeek).move(x, y);
}
}
EDIT: It just aborts. (operator instanceof returns false)
Eclipse shows me in debug, that wut
is definetly an EntitySpriteMonster
.
The only reason that I know of that code like this fails (when wut
has been verified to be of the correct type) is that the class of wut
was loaded by a different classloader than Entity
as in your class.
A class in Java is identified by it's package name, it's simple name and the classloader that loaded it. So mypackage.Entity
might be different from mypackage.Entity
if they have been loaded by separate classloaders.
This usually only happens when you use some kind of plug-in mechanism (OSGi, ...). Do you use something like this?
Problem solved!
The above use of instanceof was correct. The problem instead was:
((Inventory)palette).get(index)
returned an InventorySlot
, and not a Entity
. InventorySlot contains Entites, so I was missing to peek the first item from the container.
My correct code should be Object rawpeek = paltte.get(i).peek();
Thanks everyone for trying. And sorry for this obvious problem.
精彩评论