[英]Call unknown constructor with unknown argument length
我正在编写一个多人游戏服务器,我想从文件中动态加载所有世界数据。 这些文件应动态加载对象数组。 从文件中加载大约三到四种不同类型的对象,并且构造函数的参数长度是未知的。
保存文件的示例:
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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.