动态添加的属性在类路径文件中的Tomcat Web应用程序

问题描述:

我尝试添加属性文件到classpath动态如下动态添加的属性在类路径文件中的Tomcat Web应用程序

try { 
    File fileToAdd = new File(FILE_PATH); 
    URL u = fileToAdd.toURL(); 
    ClassLoader sysLoader = ClassLoader.getSystemClassLoader(); 
    if (sysLoader instanceof URLClassLoader) { 
    sysLoader = (URLClassLoader) sysLoader; 
    Class<URLClassLoader> sysLoaderClass = URLClassLoader.class; 

    // use reflection to invoke the private addURL method 
    Method method = sysLoaderClass.getDeclaredMethod("addURL", 
     new Class[] { URL.class }); 
    method.setAccessible(true); 
    method.invoke(sysLoader, new Object[] { u }); 
    } 
} catch (Exception e) { 
    logger.error(e.getMessage()); 
} 

,但我不能看到我的类路径此文件。当我检查它使用

System.getProperty("java.class.path") 

我不能看到我的文件在此列表中。我在这里错过了什么?

您不能添加的属性文件,你必须添加在其中的属性文件所在目录的URL作为URL:method.invoke(sysLoader, fileToAdd.getParent().toURL()); 那么你可以使用ClassLoader.getResourceAsStream("my.properties");和ClassLoader将搜索新添加的文件目录。

URLClassLoader

“这个类加载器用于从URL中既指JAR文件和目录的搜索路径加载类和资源。与被假定为一个‘/’结尾的任何URL指的是一个目录,否则URL假定为,指的是一个JAR文件,它将根据需要打开。“

+0

这就是我正在寻找的东西。谢谢 ... – ihavprobs 2011-05-26 07:20:26

也许试试这个代码,但改变java.library.path或者保持它的方式,如果你可以使用库路径来代替。

 


    /** 
    * Allows you to add a path to the library path during runtime 
    * @param dllLocation The path you would like to add 
    * @return True if the operation completed successfully, false otherwise 
    */ 
    public boolean addDllLocationToPath(final String dllLocation) 
    { 
     //our return value 
     boolean retVal = false; 
     try 
     { 
      System.setProperty("java.library.path", System.getProperty("java.library.path") + ";" + dllLocation); 
      //get the sys path field 
      Field fieldSysPath = ClassLoader.class.getDeclaredField("sys_paths"); 
      fieldSysPath.setAccessible(true); 
      fieldSysPath.set(null, null); 
      retVal = true; 
     } 
     catch (Exception e) 
     { 
      System.err.println("Could not modify path"); 
     } 
     return retVal; 
    }