0

我下面代码的目的是调用扩展 GsonLoader 的包中的所有类的 initialize() 方法。

我收到的错误是:

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)

错误行的开头有“ERROR LINE:”。

GsonLoader 基本设计(并非所有代码):

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

}

扩展 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);
    }
}

加载所有类:

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

}

子类构造函数:

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;
}

我是什么做的?

4

0 回答 0