简体   繁体   English

Java在Java中实现动态插件

[英]java implement dynamic plugins in Java

I developed an application that loads plugins dinamicaly according to this tutorial: http://solitarygeek.com/java/a-simple-pluggable-java-application , but i came across a problem. 我根据本教程开发了一个加载插件的应用程序: http : //solitarygeek.com/java/a-simple-pluggable-java-application ,但是遇到了一个问题。 In my main application i have a class with static methods, how can i access that class from inside my plugins? 在我的主应用程序中,我有一个带有静态方法的类,如何从插件内部访问该类? When i try to access the class from the loaded plugin it gives me an error that class was not found, although the plugin and the application are running. 当我尝试从已加载的插件访问该类时,尽管插件和应用程序正在运行,但它给我一个错误,即未找到该类。 Thank you 谢谢

In the plugin architecture you are not supposed to access the plugin implementation class directly. 在插件体系结构中,您不应直接访问插件实现类。 What you have at your disposal is the interface through which you'll get access to an instance of your implementation class. 您所拥有的是接口,通过该接口您可以访问实现类的实例 That obviously precludes any static methods. 显然,这排除了任何静态方法。 Refactor those methods into instance methods and expose them via the interface. 将这些方法重构为实例方法,并通过接口公开它们。

Sounds like a class loader problem. 听起来像是类加载器问题。 The class loader that loads your plugin does not see your main class. 加载插件的类加载器看不到您的主类。 Difficult to say any more without code samples. 没有代码示例,很难说更多。

I managed to resolve my problem by creting a classloader with the application classloader as parent classloader like this: 我设法通过将应用程序类加载器作为父类加载器创建类加载器来解决我的问题,如下所示:
URLClassLoader MyLoader = new URLClassLoader(new URL[]{},MyClass.class.getClassLoader()), and now, all the classes loaded in my application are visible to the plugin that is loaded with MyLoader URLClassLoader MyLoader =新的URLClassLoader(新的URL [] {},MyClass.class.getClassLoader()),现在,我的应用程序中加载的所有类对于MyLoader加载的插件都是可见的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM