简体   繁体   English

尝试从.jar加载类时发生ClassCastException

[英]ClassCastException when trying to load a class from a .jar

I am trying to launch an application at runtime from a .jar file. 我正在尝试从.jar文件在运行时启动应用程序。 So I followed the code in this thread : How to load a jar file at runtime 因此,我遵循了该线程中的代码: 如何在运行时加载jar文件

But I am having this error : 但我有这个错误:

Exception in thread "main" java.lang.ClassCastException: class net.sf.latexdraw.LaTeXDraw
    at java.lang.Class.asSubclass(Unknown Source)
    at LatexLauncher.<init>(LatexLauncher.java:17)
    at LatexLauncher.main(LatexLauncher.java:26)

Here is the code, which is quite the same from the above thread : 这是代码,与上面的线程完全相同:

File path = new File("pathToMyJAR/lib/LaTeXDraw.jar");
System.out.println(path.exists()); //return true
ClassLoader loader = URLClassLoader.newInstance(
        new URL[] { path.toURI().toURL() },
        getClass().getClassLoader()
);
Class<?> clazz = Class.forName("net.sf.latexdraw.LaTeXDraw", true, loader);
Class<? extends Runnable> runClass = clazz.asSubclass(Runnable.class);
Constructor<? extends Runnable> ctor = runClass.getConstructor();
Runnable doRun = ctor.newInstance();
doRun.run();

The above code in the LatexLauncher constructor. 上面的代码在LatexLauncher构造函数中。 The line throwing the error is : 引发错误的行是:

Class<? extends Runnable> runClass = clazz.asSubclass(Runnable.class);

It is an Eclipse project, the .jar file I want to run is in the lib folder. 这是一个Eclipse项目,我要运行的.jar文件位于lib文件夹中。 The required jars for the one I want to run (LaTeXDraw) are in lib/lib/ folder of the project. 我要运行的一个(LaTeXDraw)所需的jar在项目的lib/lib/文件夹中。 I have no idea how to fix this. 我不知道该如何解决。

My final goal is to launch the .jar application and make a Robot class performs actions onto the UI to make tests. 我的最终目标是启动.jar应用程序,并使Robot类对UI执行操作以进行测试。

Any help is welcome, Thank you for your time 欢迎任何帮助,谢谢您的时间

As mentioned in the comments, your problem is simply that net.sf.latexdraw.LaTeXDraw does not implement Runnable . 如评论中所述,您的问题很简单,就是net.sf.latexdraw.LaTeXDraw没有实现Runnable I don't really know what you were expecting to happen. 我真的不知道你期望发生什么。

Make your Robot class implement Runnable and use LaTeXDraw from within there. 使您的Robot类实现Runnable并从那里使用LaTeXDraw

public class Robot implements Runnable
{
    @Override
    public void run()
    {
       LaTeXDraw thing = new LaTeXDraw(); // or whatever
       //...
    }
}

//...
Class<?> clazz = Class.forName("package.Robot", true, loader);
Class<? extends Runnable> runClass = clazz.asSubclass(Runnable.class);
//...

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

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