我在 Eclipse 插件中使用 Apache Velocity。相应的条目已添加到 MANIFEST.MF
中:
Require-Bundle: org.apache.velocity;bundle-version="1.5.0"
Velocity 实例初始化如下:
VelocityEngine ve = new VelocityEngine();
ve.setProperty(Velocity.RUNTIME_LOG_LOGSYSTEM_CLASS, NullLogChute.class.getName());
ve.init();
我使用我的插件构建 JAR 并在多台机器上测试它。在 2 台电脑上这工作正常,但在第三台电脑上我遇到了异常:
java.lang.Exception: The specified class for ResourceManager (org.apache.velocity.runtime.resource.ResourceManagerImpl) does not implement org.apache.velocity.runtime.resource.ResourceManager; Velocity is not initialized correctly.
at org.apache.velocity.runtime.RuntimeInstance.initializeResourceManager(RuntimeInstance.java:589)
at org.apache.velocity.runtime.RuntimeInstance.init(RuntimeInstance.java:241)
at org.apache.velocity.runtime.RuntimeSingleton.init(RuntimeSingleton.java:113)
at org.apache.velocity.app.Velocity.init(Velocity.java:83)
我似乎遇到了这个异常,因为 Velocity 不适合 OGSi。谁能给我一个解决方法吗?
最佳答案
我能够使用这个解决类似的问题:https://wiki.eclipse.org/FAQ_How_do_I_use_the_context_class_loader_in_Eclipse%3F
基本上,您将当前的 Thread 类加载器设置为 Eclipse/OSGi 插件之一(或插件的类)。
下面生成的示例代码可以在普通 java 执行(作为 Java 应用程序运行)和导出 Eclipse 产品后通过插件 API 调用方面正常工作。
public class Printer {
@Override
public void myPluginApiOverride() {
Printer.main(new String[0]);
}
public static void main(final String[] args) {
// without the following class loader initialization, I get the
// following exception when running as Eclipse plugin:
// org.apache.velocity.exception.VelocityException: The specified
// class for ResourceManager
// (org.apache.velocity.runtime.resource.ResourceManagerImpl) does not
// implement org.apache.velocity.runtime.resource.ResourceManager;
// Velocity is not initialized correctly.
final ClassLoader oldContextClassLoader = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(Printer.class.getClassLoader());
// sample velocity call
final Writer writer = new PrintWriter(new OutputStreamWriter(System.out));
final VelocityContext context = new VelocityContext();
context.put("name", "World");
try {
Velocity.evaluate(context, writer, "org.apache.velocity", "Hello $name !");
writer.close();
} catch (final IOException e) {
e.printStackTrace();
}
// set back default class loader
Thread.currentThread().setContextClassLoader(oldContextClassLoader);
}
}
关于java - 使用 Velocity 作为 OSGi 包时 ResourceManager 类不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26213457/