【问题标题】:Is it possible to load library at runtime?是否可以在运行时加载库?
【发布时间】:2010-11-06 05:34:47
【问题描述】:

如果 java 库(.jar 文件)不在类路径上,有没有办法在运行时加载它?

【问题讨论】:

  • 我对库的处理不多*,但您可以尝试使用 URLClassLoader 来访问它。 * BTW - 你所说的“图书馆”是指本地人吗?
  • 不,我的意思是一个简单的 java 库。 (一个 .jar 文件)
  • 是的,有可能。我投票决定关闭它,因为谷歌“java load jar dynamic”给了我一些不错的 SO 答案和一些其他有用的例子。
  • @Andrew Thompson - 您的方法有效,但一次只加载一个类。有没有办法加载整个库?

标签: java urlclassloader


【解决方案1】:
URLClassLoader child = new URLClassLoader (myJar.toURL(), this.getClass().getClassLoader());
Class classToLoad = Class.forName ("com.MyClass", true, child);
Method method = classToLoad.getDeclaredMethod ("myMethod");
Object instance = classToLoad.newInstance ();
Object result = method.invoke (instance);

来源:How should I load Jars dynamically at runtime?

【讨论】:

  • Important Comment From Source: 使用这种方法,您需要确保不会为每个类多次调用此加载方法。由于您正在为每个加载操作创建一个新的类加载器,它无法知道该类之前是否已经加载过。这可能会产生不良后果。例如单例不工作,因为类被加载了几次,所以静态字段存在多次
猜你喜欢
  • 2010-09-28
  • 1970-01-01
  • 1970-01-01
  • 2011-10-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多