下面部分显示的类包含一个main方法。当我运行代码时,我看到NullPointerException
(NPE)然后出现错误消息 - “无法找到主类,程序将退出”。我的理解是,如果我得到NPE,这意味着代码正在运行,即JRE找到了一个main
方法来开始执行,那么为什么我会收到错误消息?
这是控制台输出
java.lang.ExceptionInInitializerError
Caused by: java.lang.NullPointerException
at com.MyWorldDemo.getValue(MyWorldDemo.java:57)
at com.MyWorldDemo.<clinit>(MyWorldDemo.java:23)
Exception in thread "main"
简而言之:
这是一些代码示例
class MyClass {
private final static String username = getData("username"); // ERROR HERE
private static Properties prop;
// more variables
static {
prop = new Properties();
try {
FileInputStream fis = new FileInputStream("MyDB.properties");
prop.load(fis);
} catch (IOException ex) {
ex.printStackTrace();
}
}
// this method will assign a value to my final variable username.
public static String getData(String props) {
String property = prop.getProperty(props);// ERROR HERE !!!
return property;
}
}
答案 0 :(得分:2)
你在MyWorldDemo
的第23行进行静态初始化,调用方法getValue
,然后在第57行引起NPE,因此该类无法实例化,因此主方法不能叫做。它可能看起来像:
class MyWorldDemo {
private static String foo = getValue("username");
private static Properties prop;
// This happens too late, as getValue is called first
static {
prop = new Properties();
try {
FileInputStream fis = new FileInputStream("MyDB.properties");
prop.load(fis);
} catch(IOException ex) {
ex.printStackTrace();
}
}
// This will happen before static initialization of prop
private static String getValue(String propertyValue) {
// prop is null
return prop.getProperty(propertyValue);
}
public static void main(String args[]) {
System.out.println("Hello!"); // Never gets here
}
}
答案 1 :(得分:2)
静态变量的初始化取决于它在代码中的位置(变量从上到下初始化)。在你的代码中
private final static String username = getData("username"); // ERROR HERE
private static Properties prop;
// more variables
static {
prop = new Properties();
try {
FileInputStream fis = new FileInputStream("MyDB.properties");
prop.load(fis);
} catch (IOException ex) {
ex.printStackTrace();
}
}
prop
对象将在静态块中username
之后初始化,但由于初始化username
prop
是必要的,并且尚未初始化,因此您将获得NPE。也许将您的代码更改为:
private static Properties prop = new Properties();
private final static String username = getData("username");
static {
try {
FileInputStream fis = new FileInputStream("MyDB.properties");
prop.load(fis);
} catch (IOException ex) {
ex.printStackTrace();
}
}