Dynamically Loading Classes with Generic Supertypes

327 Views Asked by At

The purpose of my code below is to call the initialize() method all of the classes in a package that extend GsonLoader.

The error which I am receiving is:

java.lang.InstantiationException: com.salesy.utility.gson.impl.NPCSpawnsLoader
at java.lang.Class.newInstance(Unknown Source)
at com.salesy.utility.providers.FileClassLoader.getClassesInDirectory(FileClassLoader.java:22)
at com.salesy.utility.gson.GsonInitiator.initiate(GsonInitiator.java:18)
at com.salesy.Salesy.main(Salesy.java:43)

The error line has "ERROR LINE:" at the beginning of the line.

GsonLoader basic design (not all of the code):

public abstract class GsonLoader<T> {

/**
 * The child class must initialize to populate the hashmap of values.
 */
public abstract void initialize();


/**
 * The file location which data will be read from
 * 
 * @return The list of data
 */
public abstract String getFileLocation();

}

Example of a class extending GsonLoader:

public class NPCSpawnsLoader extends GsonLoader<NPCSpawnsLoader>{

@Override
public String getFileLocation() {
    return "data/loading/spawns.json";
}

@Override
public void initialize() {
    for (NPCSpawnsLoader spawns : load()) {
        hashmap.put(spawns.getId(), spawns);
    }
}

Loading of all the classes:

public class GsonInitiator {

/**
 * Loads all of the gson classes
 */
public static void initiate() {
    int count = 0;
    for (Object class1 : FileClassLoader.getClassesInDirectory(GsonLoader.class.getPackage().getName() + ".impl")) {
        GsonLoader<?> loader = (GsonLoader<?>) class1;
        loader.initialize();
        count++;
    }
    logger.info("Completely loaded " + count + " gson-loading classes.");
}

private static final Logger logger = Logger.getLogger(GsonLoader.class.getName());

}

Child class constructor:

public NPCSpawnsLoader(int x, int y, int z, int id, Direction direction) {
    this.id = id;
    this.x = x;
    this.y = y;
    this.z = z;
    this.direction = direction;
}

FileClassLoader#getClassesInDirectory:

public static List<Object> getClassesInDirectory(String directory) {
    List<Object> classes = new ArrayList<Object>();
    for (File file : new File("./src/" + directory.replace(".", "/")).listFiles()) {
        try {
            [ERROR LINE:]Object objectEvent = (Class.forName(directory + "." + file.getName().replace(".java", "")).newInstance());
            classes.add(objectEvent);
        } catch (InstantiationException | IllegalAccessException
                | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
    return classes;
}

What am I to do?

0

There are 0 best solutions below