反射会把你带到某个地方......我不知道它是否是首选方法。
你可以做这样的事情。让每个怪物类型实现一个接口,如下所示:
public interface Monster {
public boolean canBeCreated ( );
}
然后你可以有一个怪物创造者,像这样:
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
public class MonsterCreator {
private Monster[] monsterTypes;
public MonsterCreator ( ) {
monsterTypes = new Monster[2];
monsterTypes[0] = new Zombie ( );
monsterTypes[0] = new Skeleton ( );
}
public void tick ( ) {
for ( Monster m : monsterTypes ) {
if ( m.canBeCreated ( ) ) {
try {
Constructor< ? >[] constr = m.getClass ( )
.getConstructors ( );
Monster toAdd = ( Monster ) constr[0].newInstance ( );
MonsterContainer.add ( toAdd );
} catch ( InstantiationException | IllegalAccessException
| IllegalArgumentException | InvocationTargetException e ) {
e.printStackTrace ( );
}
}
}
}
}
值得一试... :)
当然,怪物类型的事情可以通过类似于链接到类类型的枚举常量映射来更整洁地完成......再次,这只是为了示例。只是想在问题结束之前发布这个!