【发布时间】:2018-05-05 02:30:30
【问题描述】:
我正在编写一个程序,让我的学生参与一个基本的 AI 游戏(类似于 IBM 多年前所做的事情)。这个想法很简单。每个人都有一个游戏项目jar,以及他们的AI类MyAI.java(其中implements AbstractAI)。该结构一切正常,他们可以将代码写入他们的 AI 类,并将其提交到一个公共文件夹。少数学生提交后的文件夹结构为:
school/stud1/MyAI.class
school/stud2/MyAI.class
我还编写了一些我认为(回想起来很天真)可以将所有类加载并实例化为ArrayList 的代码。问题是我最终得到了当前类的 x 个实例的 ArrayList。
我发现了一些类似的问题,但接受的答案在这种情况下不起作用。
一些 Loader 类(没有美化,只是一个概念证明)包括在下面:
/**
* Load a single ai from a given location
* @param location The path where the ai is: example: c:\\tourney
* @param className The complete class: "org.mrd.Tournament.MyAI"
* @return The instance of AbstractAI loaded
*/
public static AbstractAI loadAI(String location, String className){
Object o = null;
try {
o = new URLClassLoader( new URL[]{new File(location).toURI().toURL()}
).loadClass(className).newInstance();
} catch ...{
}
if (o == null) return null;
return (AbstractAI)o;
}
/**
* Load all current files in tournament folder.
*/
public static ArrayList<AbstractAI> loadCurrentTourneyFiles(){
File dirs = new File("d:\\tourney\\school");
//list of all file names
ArrayList<String> names = new ArrayList<String>(Arrays.asList(dirs.list()));
//Create an arraylist for all loaded AIs and load them.
ArrayList<AbstractAI> arar = new ArrayList();
for (String dir:names){
arar.add(loadAI(dirs.getAbsolutePath() + "\\" + dir, "org.mrd.Tournament.MyAI"));
}
return arar;
}
最相关的主题: Java ClassLoader: load same class twice Java - how to load different versions of the same class?
【问题讨论】:
-
闻起来像 XY 问题。必须是更好的方法。
-
这看起来是一个有趣的项目,但我希望有一个更简单的解决方案。
标签: java classloader