下面我的代码的目的是调用initialize()方法扩展GsonLoader的包中的所有类。
我收到的错误是:
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;
}
我该怎么办?