代码之家  ›  专栏  ›  技术社区  ›  Zombies

Java:通过运行时修改系统属性

  •  3
  • Zombies  · 技术社区  · 15 年前

    我有一个已经运行的JAR文件。它是Selenium RC服务器。我希望能够更改jvm httpproxy.host/port/etc系统值。一方面,我可以修改源代码并将此功能添加到中。需要一些时间。还有其他可能的方法吗?就像让我自己的jar(它将设置这些jvm属性)在同一个jvm实例中调用SeleniumRC(这样它就能够修改其jvm变量的值)?

    2 回复  |  直到 9 年前
        1
  •  5
  •   mdma    15 年前

    可以在命令行上定义系统属性,使用

    -DpropertyName=propertyValue
    

    所以你可以写

    java -jar selenium-rc.jar -Dhttp.proxyHost=YourProxyHost -Dhttp.proxyPort=YourProxyPort
    

    Java - the java application launcher ,

    编辑:

    您可以编写一个包装器,它是一个应用程序启动程序。很容易模拟调用 main 使用反射的类中的方法。然后还可以通过以下方式设置系统属性: System.setProperty 在启动最终应用程序之前。例如,

    public class AppWrapper
    {
    /* args[0] - class to launch */     
       public static void main(String[] args) throws Exception
       {  // error checking omitted for brevity
          Class app = Class.forName(args[0]);
          Method main = app.getDeclaredMethod("main", new Class[] { (new String[1]).getClass()});
          String[] appArgs = new String[args.length-1];
          System.arraycopy(args, 1, appArgs, 0, appArgs.length);
          System.setProperty("http.proxyHost", "someHost");
          main.invoke(null, appArgs);
       }
    }
    
        2
  •  2
  •   user100464    9 年前

    使用 System.setProperty() 方法。