1

下面部分显示的类包含一个 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"  

简而言之:

  • 用户名存储在属性文件中。
  • 属性文件就像这样 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;
    }
}
4

2 回答 2

2

您在第 23 行有一个静态初始化,MyWorldDemo它正在调用方法getValue,然后在第 57 行导致 NPE,因此无法实例化该类,因此无法调用 main 方法。它可能看起来像:

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
    }
}
于 2012-07-26T18:37:37.237 回答
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();
    }
}
于 2012-07-26T18:46:34.553 回答