错误:无法找到或加载主类,但在类路径中缺少.jar时有效吗?

时间:2018-04-06 23:20:15

标签: java selenium terminal javac

我正在关注本教程:https://www.youtube.com/watch?v=UlY_6N98WWs&list=PLIBI8eaaUGfSupVFlMBefGodvWQ9ydq51&index=4 并得到了这个错误:

$ java -classpath selenium-server-standalone-3.11.0.jar HelloWorld 
Error: Could not find or load main class HelloWorld

但如果我运行$ java HelloWorld,它就可以正常运行,并说

Exception in thread "main" java.lang.NoClassDefFoundError: org/openqa/selenium/firefox/FirefoxDriver at 
HelloWorld.main(HelloWorld.java:13) Caused by: 
java.lang.ClassNotFoundException: 
org.openqa.selenium.firefox.FirefoxDriver at 
java.net.URLClassLoader.findClass(URLClassLoader.java:381) at 
java.lang.ClassLoader.loadClass(ClassLoader.java:424) at 
sun.misc.Launcher$AppClassLoader.loadClass(Launcher.j

我在Mac终端上,我尝试使用CLASSPATH .并空白。我的$PATH变量为/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin,似乎没问题。

我尝试查看这些页面以获得解决方案: https://docs.oracle.com/javase/tutorial/essential/environment/paths.html https://docs.oracle.com/javase/7/docs/technotes/tools/windows/classpath.html What does "Could not find or load main class" mean?

似乎我的班级路径工作得很好,但其他的东西是不好的?

HelloWorld.java

/**
 * Import FirefoxDriver and By from selenium jar
 */
import org.openqa.selenium.By;
import org.openqa.selenium.firefox.FirefoxDriver;

public class HelloWorld{

    public static void main(String args[]) throws Exception{

        // Create a Firefox browser instance
        FirefoxDriver driver = new FirefoxDriver();

        // Navigate to google home page
        driver.get("https://www.google.co.in/");

        // Type hello world in the search field
        driver.findElement(By.name("q")).sendKeys("Hello World");

        // Wait for 10 seconds
        Thread.sleep(10*1000);

        // Close the browser instance
        driver.quit();

    }
}

从以下位置下载Selenium Standalone Server 3.11.0版: https://www.seleniumhq.org/download/

我在Mac OS 10.13.3上运行。

1 个答案:

答案 0 :(得分:1)

显然我需要通过将:.附加到selenium-server-standalone-3.11.0.jar将当前目录附加到类路径。

$ java -classpath selenium-server-standalone-3.11.0.jar:. HelloWorld 

特别感谢lanoxx对https://stackoverflow.com/a/18093929/2423194的评论帮助我:

  

当我尝试使用第三方运行一个类时,我遇到了这个问题   图书馆。我像这样调用java:java -cp ../third-party-library.jar   com.my.package.MyClass;这不起作用,而是有必要的   将本地文件夹添加到类路径中(由:分隔,如   这个:java -cp ../third-party-library.jar:。 com.my.package.MyClass,   它应该工作

还要感谢Sam Orozco在我打字的时候评论了这个答案。