从位于JAR内的类创建对象?

时间:2017-01-15 23:43:44

标签: java jar

注意

标记为重复?我肯定是错的,但我无法看到为什么重复的问题会有所帮助。由于之前的评论,我们已经建立了一些进展 - 这些评论显然已经显示了我实际需要的解决方案,而不是将其标记为一些完全无用的信息的副本。

从位于JAR内的类创建对象?

我目前正在尝试创建一个系统来管理来自另一个Java项目的.jar插件。我们的想法是它应该能够在一个名为Plugin的类中创建一个对象,该类位于另一个.jar文件中,然后加载然后像任何其他Java类一样初始化该类。

进度

我已设法找到.jar我希望使用File包中的java.io加载类。我用JarFile搞砸了一会儿,但意识到我无法实现我使用它之后的状态。总是很开心玩新的东西!

研究

在这段时间里,我一直坐在这里,我在 Stackoverflow 上找到了几个帖子,为了实现我的目标,我们都找不到任何一个帖子:< / p>

在我看来,好像这不是一件容易的事。如果证明对我的问题有任何用处,那么对这两种资源的任何想法都将受到高度赞赏。

而且

这是一个.jar文件,我想将一个类加载到一个对象中,同时加载该类的应用程序启动并运行,以便用户能够添加更多插件,重启并享受!

也许有人可以指出我正确的方向?

实施例

有人建议我附上一个我正在尝试的例子 - 有人对link me to one of their answers另一个问题也很好。

以下是我尝试使用该方法的内容:

// ...
// The ‘folderPlugins’ is a file set to the folder containing all plugins
File plugin = new File(folderPlugins.getPath() + "/" + jar);

URLClassLoader classLoader = null;

// First try / catch block used to instantiate the `URLClassLoader` works like a charm
try
{
    classLoader = new URLClassLoader(new URL[] {plugin.toURI().toURL()});
}
catch (MalformedURLException ex)
{
    System.out.println("0");

    Logger.getLogger(Plugins.class.getName())
            .log(Level.SEVERE, null, ex);

    System.exit(0);
}

Class cls = null;

// Second try / catch block used to load up the class also works like a charm!      
try
{
    cls = classLoader.loadClass("x.X");

    // This nicely outputs into the console as the loaded class ‘class x.X’
    System.out.println("Cls: " + cls);
}
catch (ClassNotFoundException ex)
{
    System.out.println("1");

    Logger.getLogger(Plugins.class.getName())
            .log(Level.SEVERE, null, ex);

    System.exit(0);
}

// This is where ‘hell breaks lose’.        
try
{
    // Rather than ending up in here, the ‘catch’ block is used
    Object object = cls.newInstance();
}
catch (InstantiationException | IllegalAccessException ex)
{
    // Console prints ‘2’
    System.out.println("2");

    Logger.getLogger(Plugins.class.getName())
            .log(Level.SEVERE, null, ex);

    System.exit(0);
}
// ...

上一个try / catch块生成的部分错误如下:

...
java.lang.InstantiationException: textarea.TextArea
...
Caused by: java.lang.NoSuchMethodException: textarea.TextArea.<init>()    at
java.lang.Class.getConstructor0(Class.java:3082)  at
java.lang.Class.newInstance(Class.java:412)
...

此错误对应于与上一个try块中唯一一个错误发生相同的行。

0 个答案:

没有答案
相关问题