java - 使用未知参数长度调用未知构造函数

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

最佳答案

要具有通用负载:

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/

相关文章:

java - eclipse可以调试或运行一个项目中的两个程序

类型参数隐藏中的 Java 泛型

java - 如何理解 javap 输出中的 LocalVariableTable 区域

javascript - 如何在 AngularJS 中处理和显示对象数组

javascript - 对象在 react render() 内部似乎是空的,即使之前的日志记录证明它不是

c# - 通过将类名作为字符串提供来获取引用程序集中的类型?

java - GXT-3 : HTML code is displayed rather than the image

javascript - JS中如何使用流

xml - 对 XML 文件使用内联 XSLT

c# - 获取对象实例上自定义属性的*值*?