I have a base Entity class:
public class Entity
{
abstract int getTypeID();
}
The method int getTypeID() returns a number that is unique to that class:
public class OneEntity extends Entity
{
int getTypeID()
{
return 1; // Actually defined in a constants class
}
}
Now I want to be able to safely cast it and assign it.
I can do it this way:
public void castTheEntityAndDoSomething(Entity ent)
{
if (isType(ent, 1)) // this is the 1 from the OneEntity class
{
OneEntity oneEnt = (OneEntity)ent;
// ... and then do something
}
}
public bool isType(Entity ent, int type)
{
return ent.getTypeID() == type;
}
But what I’d like to do is combine the cast and the type check in one line.
Something like:
if (OneEntity oneEnt = entityCast(ent, 1))
{
// use a method specific to the OneEntity class
}
Is this possible? What does the method look like?
It would be even better if I could use the subclass name as an argument of the safe casting method.
EDIT:
So I’ve written this method to avoid the type id etc. etc.
@SuppressWarnings("unchecked")
public static <T extends Entity> T castEntity(Entity ent)
{
if (ent instanceof T)
{
return (T)ent;
}
return null;
}
But it has this error:
Cannot perform instanceof check against type parameter T. Use instead its erasure Entity since generic type information will be erased at runtime
What do I need to do to fix this compile error? Is this even going in the right direction?
In case you have defined this
typeIdfor the sole purpose of casting, then please don’t do that and useinstanceofoperator instead.Then you just need to do something like this,
Now, taking your example here,
Suppose this
ifstatement of yours work and yourentityCast()method returnOneEntity. Don’t you think you are again getting that returned value in typeEntity. Hence spoiling the whole purpose.So, please explain what are you trying to do exactly.