【问题标题】:Loading versions of the same class (Java)加载同一类的版本(Java)
【发布时间】: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 问题。必须是更好的方法。
  • 如何使用compilation-toolbox
  • 这看起来是一个有趣的项目,但我希望有一个更简单的解决方案。

标签: java classloader


【解决方案1】:

你可以尝试使用compilation-toolbox,这个想法是你会尝试使用以下sn-p加载每个学生jar:

 JavaSourceCompiler javaSourceCompiler = new JavaSourceCompilerImpl();
 JavaSourceCompiler.CompilationUnit compilationUnit = javaSourceCompiler.createCompilationUnit();
 compilationUnit.addClassPathEntry("ai_student1.jar");
 compilationUnit.addClassPathEntry("abstract_ai.jar");


  String aiProvider =  "package com.ai;\n" +
      "  import com.ai.student.AI;\n" +
        "import com.ai.AbstractAI;\n" + 
     "   public class AIProvider {\n" +
       "          public AbstractAI get() {\n" +
      "            return new AI();\n" +
      "        }\n\n" +
       "    }";

ClassLoader classLoader = javaSourceCompiler.compile(compilationUnit);
Class aIProvider = classLoader.loadClass("com.ai.Provider");

【讨论】:

    猜你喜欢
    • 2012-07-30
    • 2010-12-14
    • 2011-08-13
    • 1970-01-01
    • 2017-11-01
    • 1970-01-01
    • 2018-03-14
    • 2010-09-08
    • 1970-01-01
    相关资源
    最近更新 更多