我正在编写一个多人游戏服务器,我想动态地从文件加载所有世界数据。这些文件应该动态加载对象数组。将从文件中加载大约三到四种不同类型的对象,并且构造函数参数长度未知。
保存文件的示例:
arg1, arg2, arg3, arg4
被分割成一个数组
[arg1, arg2, arg3, arg4]
然后应该使用这些参数调用构造函数
new NPC(arg1, arg2, arg3, arg4)
这是我现在的方法
public static <T> void load(String path, Class<T> type) {
path = dataDir + path;
String content = Util.readFile(path);
String[] lines = content.split("\n");
// T[] result = new T[lines.length]; Type paramater 'T' can not be instantiated directly.
for (int i = 0; i < lines.length; i++) {
String[] args = lines[i].split(", ");
// result[i] = new T(args[0], args[1]...); Should add a T to the array with args 'args'
}
// return result
}
它的名字是这样的
Npc[] npcs = DataLoader.load("npcs.dat");
最佳答案
要具有通用负载:
public static <T> T[] load(String path, Class<T> type) ...
在每个类中声明采用字符串数组的构造函数:
public Npc(String[] args)
或 public Npc(String... args)
然后使用反射来实例化泛型类型:
// instantiate a generic array
T[] result = (T[]) Array.newInstance(type, length);
// parameterized constructor of generic type, e.g. new T(String[])
Constructor<T> constructorOfT = type.getConstructor(String[].class);
// call the constructor for every position of the array
result[i] = constructorOfT.newInstance(new Object[] { args });
由于可以使用任何类型调用 load
,否则构造函数可能不会退出,因此捕获反射异常:
catch (ReflectiveOperationException e) {
// means caller did not call one of the supported classes (Npc)
// or the class does not have the expected constructor
// react in some way
e.printStackTrace();
}
关于java - 使用未知参数长度调用未知构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38470760/