调用未知参数长度为

时间:2016-07-20 01:04:59

标签: java arrays reflection

我正在编写多人游戏服务器,我想动态加载文件中的所有世界数据。这些文件应该动态加载一个对象数组。将从文件加载大约三种或四种不同类型的对象,并且构造函数参数长度未知。

已保存文件的示例:

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");

1 个答案:

答案 0 :(得分:1)

要拥有通用负载:

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();
}
相关问题