mardi 19 juillet 2016

Call unknown constructor with unknown argument length

I'm writing a multiplayer game server, and I'd like to load all the world data from files dynamically. These files should dynamically load an array of objects. There will be about three or four different types of objects to load from files, and there constructor argument lengths are unknown.

An example of a saved file:

arg1, arg2, arg3, arg4

Which gets split into an array

[arg1, arg2, arg3, arg4]

Which should then call a constructor with those arguments

new NPC(arg1, arg2, arg3, arg4)

Here's the method I have right now

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
}

And it's called like this

Npc[] npcs = DataLoader.load("npcs.dat");





Aucun commentaire:

Enregistrer un commentaire