在运行时将文件添加到java类路径

在运行时将文件添加到java类路径

本文介绍了在运行时将文件添加到java类路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在运行时向java类路径添加文件(不一定是jar文件)。
具体来说,该文件已存在于类路径中,我想要的是我是否可以将此文件的修改后的副本添加到类路径中。

Is it possible to add a file (not necessarily a jar file) to java classpath at runtime.Specifically, the file already is present in the classpath, what I want is whether I can add a modified copy of this file to the classpath.

谢谢,

推荐答案

您只能将文件夹或jar文件添加到类加载器。因此,如果您有一个类文件,则需要先将其放入相应的文件夹结构中。

You can only add folders or jar files to a class loader. So if you have a single class file, you need to put it into the appropriate folder structure first.

是一个相当丑陋的黑客,它在运行时添加到SystemClassLoader:

Here is a rather ugly hack that adds to the SystemClassLoader at runtime:

import java.io.IOException;
import java.io.File;
import java.net.URLClassLoader;
import java.net.URL;
import java.lang.reflect.Method;

public class ClassPathHacker {

  private static final Class[] parameters = new Class[]{URL.class};

  public static void addFile(String s) throws IOException {
    File f = new File(s);
    addFile(f);
  }//end method

  public static void addFile(File f) throws IOException {
    addURL(f.toURL());
  }//end method


  public static void addURL(URL u) throws IOException {

    URLClassLoader sysloader = (URLClassLoader) ClassLoader.getSystemClassLoader();
    Class sysclass = URLClassLoader.class;

    try {
      Method method = sysclass.getDeclaredMethod("addURL", parameters);
      method.setAccessible(true);
      method.invoke(sysloader, new Object[]{u});
    } catch (Throwable t) {
      t.printStackTrace();
      throw new IOException("Error, could not add URL to system classloader");
    }//end try catch

   }//end method

}//end class

访问受保护的方法 addURL 需要反射。如果存在SecurityManager,则可能会失败。

The reflection is necessary to access the protected method addURL. This could fail if there is a SecurityManager.

这篇关于在运行时将文件添加到java类路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 17:14