简体   繁体   中英

how to add a file to Java Classpath at Runtime?

I am creating a feature file at runtime and trying to access the file once it is created . I have followed all the methods given here .

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

[Edit] Adding Sample code

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

Try this one on for size.

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

This edits the system class loader to include the given file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM