[英]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. 这将编辑系统类加载器以包括给定的文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.