创建对象抛出NullPointerException

时间:2017-07-04 07:05:40

标签: java nullpointerexception

我在Java中使用以下代码将java.lang.NullPointerException抛出到我创建新实例的行。

import java.util.Properties;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class Test {

    public static void main(final String... args) {

        Properties seleniumProperties = new Properties();
        seleniumProperties.setProperty("webdriver.gecko.driver", "<PATH_TO_DRIVER>");
        System.setProperties(seleniumProperties);

        WebDriver driver = new FirefoxDriver();

    }

}

行号14是WebDriver driver = new FirefoxDriver();,这是异常的堆栈跟踪:

Exception in thread "main" java.lang.NullPointerException
    at java.lang.String.startsWith(String.java:1405)
    at java.lang.String.startsWith(String.java:1434)
    at java.util.jar.JarFile.isKnownNotToHaveSpecialAttributes(JarFile.java:594)
    at java.util.jar.JarFile.checkForSpecialAttributes(JarFile.java:552)
    at java.util.jar.JarFile.hasClassPathAttribute(JarFile.java:518)
    at java.util.jar.JavaUtilJarAccessImpl.jarFileHasClassPathAttribute(JavaUtilJarAccessImpl.java:37)
    at sun.misc.URLClassPath$JarLoader.getClassPath(URLClassPath.java:1186)
    at sun.misc.URLClassPath.getLoader(URLClassPath.java:522)
    at sun.misc.URLClassPath.getNextLoader(URLClassPath.java:484)
    at sun.misc.URLClassPath.getResource(URLClassPath.java:238)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:365)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:362)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:361)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at Test.main(Test.java:14)

1 个答案:

答案 0 :(得分:1)

我想我发现了这个问题。使用System.setProperties可能会删除JVM使用的所有关键属性。我将代码替换为System.setProperty,如下所示,现在它可以正常工作。

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class Test {

    public static void main(final String... args) {

        /*
        Properties seleniumProperties = new Properties();
        seleniumProperties.setProperty("webdriver.gecko.driver", "<PATH_TO_DRIVER>");
        System.setProperties(seleniumProperties);
        */
        System.setProperty("webdriver.gecko.driver", "<PATH_TO_DRIVER>");
        WebDriver driver = new FirefoxDriver();

    }

}
相关问题