下面部分显示的类包含一个主方法。当我运行代码时,我看到一个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"
简而言之:
- username存储在属性文件中
- 属性文件类似于username=superman。。。。等等
这是的一些代码示例
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;
}
}
静态变量的初始化取决于它在代码中的位置(变量从上到下初始化)。在您的代码中
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();
}
}
在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
}
}