1:
我有一个字典,字符串作为键,类作为值,这包含我在游戏中的“实体”列表.
private static Map entitiesList = new HashMap();
public static void initEntitiesList()
{
entitiesList.put("npc_something", NpcSomething.class);
entitiesList.put("npc_thing", NpcThing.class);
entitiesList.put("npc_stuff", NpcStuff.class);
...
}
2:
这是一个示例层次结构.
Entity (abstract)
^
Mobile (abstract)
^
BaseCreature (abstract)
^
NpcSomething
-Entity包含一个名为“public void Input(String args)”的方法,
可以在其他实体中重新定义.
– 当我在NpcSomething上调用Input(“x”)时,它应该从它自己的类到Entity的类执行超级(arg)链.
– 上面的所有类都有一个允许字符串作为参数的构造函数.
3:
我有一个独立的静态方法用于创建我的实体的新实例,如下所示:
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 failed.
//Method method = entClass.getMethod("input", new Class[] { ent.getClass() });
//method.invoke(ent, new Object[] {ent});
//java.lang.NoSuchMethodException: entities.NpcSomething.input(entities.NpcSomething)
//this here is really out of place, as i plan on having a hundred of entities and even more...
//if (entClass.isInstance(NpcSomething.class))
//i tried stuffs related to:
//T t = entClass.cast(ent);
//but i could not understand it at all even with documentation.
//basically i want to cast ent to entClass to call Input.
//right now, the line under calls Input on an Entity class, which is what i want to avoid.
ent.Input("Stuffs");
}
catch (InstantiationException ex) { ex.printStackTrace(); }
catch (IllegalAccessException ex) { ex.printStackTrace(); }
catch (IllegalArgumentException ex) { ex.printStackTrace(); }
catch (InvocationTargetException ex) { ex.printStackTrace(); }
catch (NoSuchMethodException ex) { ex.printStackTrace(); }
catch (SecurityException ex) { ex.printStackTrace(); }
}
}
4:
我的问题.
EntCreator.createEntity("NpcSomething", "stuffs");
EntCreator.createEntity("NpcThing", "stuffs");
EntCreator.createEntity("NpcStuff", "stuffs");
我想调用Input();在NpcSomething上,
我想调用Input();在NpcThing上,
我想调用Input();在NpcStuff上.
然后那些3将调用它们各自的超类代码,依此类推,直到它们到达实体.
那些被转换为实体,带有“ent =(Entity)entClass.getDec …”,因为我有Mobile,还有Item,以及其他继承Input的类.
然后使用该Entity,找到正确的子类,并调用该子类的Input.
短线问题:将“NpcSomething”创建为“Entity”,然后将实体强制转换为“NpcSomething的类”以调用方法“Input(args)”.
5:
快速问题的答案.
-Q:为什么要这样做?
-A:使用预创建参数创建实体,例如:创建(“NpcSomething”,“health 20 healthmax 25”).
-Q:为什么不使用instanceof?
-A:在静态类中我需要超过200个instanceof,这将是一个糟糕的编程习惯.
-Q:为什么不在实体本身中移动输入法?
-A:我有很多不同的实体,有不同的价值观,
例如:
NpcThing,唯一的飞行手机将有飞速,飞行能……
ItemScroll,有text,textColor,textFont ……
这些是我无法放置在Entity中的东西,因为它需要instanceof,这对于ents来说是一种不好的做法.
-Q:你想将NpcSomething投射到实体吗?
-A:再读一遍.
-Q:你能提供更多信息吗?
-A:我也喜欢这样做.
-Q:你为什么不宣布为NpcSomething?
-A:因为ent可能是ItemStuff,ModelHouse等,它们不是继承自Mobile或BaseCreature ……
6:
我没有找到如何做我想要的好的实际例子.
我在文档中找不到任何特别的内容.
欢迎任何帮助.