我有一个字典,字符串作为键,类作为值,这包含我在游戏中的"实体"列表.
private static Map<String, Class> entitiesList = new HashMap<String, Class>();
public static void initEntitiesList()
{
entitiesList.put("npc_something", NpcSomething.class);
entitiesList.put("npc_thing", NpcThing.class);
entitiesList.put("npc_stuff", NpcStuff.class);
...
}
Run Code Online (Sandbox Code Playgroud)
这是一个示例层次结构.
Entity (abstract)
^
Mobile (abstract)
^
BaseCreature (abstract)
^
NpcSomething
Run Code Online (Sandbox Code Playgroud)
-Entity包含一个名为的方法"public void Input(String args)",可以在其他实体中重新定义.
- 当我调用Input("x")NpcSomething时,它应该super(arg)从它自己的类到Entity的类做一个链.
- 上面的所有类都有一个允许字符串作为参数的构造函数.
我有一个独立的静态方法用于创建我的实体的新实例,如下所示:
public static boolean createEntity(String entName, String args)
{
Class<?> entClass = null;
if ((entClass = entitiesList.get(entName)) != null)
{
Entity ent;
try
{
ent = (Entity)entClass.getDeclaredConstructor(String.class).newInstance("");
//this here …Run Code Online (Sandbox Code Playgroud)