In the following code I am returning a class that extends the type of Entity given the name of the class (it then corrects it so that Class.forName
can find it properly).
How can I modify this so that I can still return a class that extends Entity without using @SuppressWarnings("unchecked")
?
I tired a few variations using T
and just ?
but couldn't come up with an answer.
@SuppressWarnings("unchecked")
public static Class<? extends Entity> getProjectile(String name) {
if (name.equalsIgnoreCase("ARROW"))
name = "Arrow";
else if (name.equalsIgnoreCase("ENDERPEARL"))
name = "EnderPearl";
else if (name.equalsIgnoreCase("EXPERIENCEORB"))
name = "ExperienceOrb";
else if (name.equalsIgnoreCase("FIREBALL"))
name = "Fireball";
else if (name.equalsIgnoreCase("FIREWORK"))
name = "Firework";
else if (name.equalsIgnoreCase("SMALLFIREBALL"))
name = "SmallFireball";
else if (name.equalsIgnoreCase("SNOWBALL"))
name = "Snowball";
else
name = "Egg";
try {
return (Class<? extends Entity>) Class.forName("org.bukkit.entity." + name);
} catch (ClassNotFoundException e) {
return Egg.class;
}
}
You can't.
Class.forName(String)
is declared as returning a reference of typeClass<?>
which you then have to cast if you want it to conform toClass<? extends Entity>
This cast is unsafe so the compiler warns you.The alternative is to have the actual
Class
objects in theif-else
block instead of the names.