如何在运行时将文件添加到Java Classpath?

时间:2017-06-14 18:58:40

标签: java cucumber

我正在运行时创建一个功能文件,并在创建文件后尝试访问该文件。我遵循了here给出的所有方法。

 1. Is there a way to refresh the project at runtime ?
 2. Is there any other way to load the file in classpath ?

[编辑]添加示例代码

  public static void createFeatureFile(String featurePath) throws IOException{

    FileWriter writer = new FileWriter(featurePath);

    writer.append("Feature: Test ");
    writer.append("\n");
    writer.append("\n");
    writer.append("@test");
    writer.append("\n");
    writer.append("Scenario : add fruits");
    writer.append("\n");
    writer.append("Given I have 1 apple and 1 orange");
    writer.append("\n");
    writer.append("Then I add both"");
    writer.append("\n");                    

    writer.flush();
    writer.close();    

    File file =new File(featurePath);
    addFileAtRunTime(file);           

}

  private static void addFileAtRunTime(File file) throws Exception {
        Method method = URLClassLoader.class.getDeclaredMethod("addURL", new Class[]{URL.class});
        method.setAccessible(true);
        method.invoke(ClassLoader.getSystemClassLoader(), new Object[]{file.toURI().toURL()});
    }

1 个答案:

答案 0 :(得分:0)

尝试使用此尺寸。

   private static void addFileAtRunTime(File file) throws Exception {
        Method method = URLClassLoader.class.getDeclaredMethod("addURL", new Class[]{URL.class});
        method.setAccessible(true);
        method.invoke(ClassLoader.getSystemClassLoader(), new Object[]{file.toURI().toURL()});
    }

这会编辑系统类加载器以包含给定文件。