- 報錯原因:在一個類中寫了一個public String getContent()方法和一個main()方法,getContent()方法中包含了getClass()方法,在main()方法中直接調用了getContent()就出現如題的錯誤。這樣一樣
- 解決方法:先實例化類,然後再調用getContent()就沒有問題了
-
- GetProperties gp = new GetProperties();
- String s = gp.getCotent();
- 說明:在靜態方法中,不能直接訪問非靜態成員(包括方法和變量)。因爲,非靜態的變量是依賴於對象存在的,對象必須實例化之後,它的變量纔會在內存中存在。例如一個類 Student 表示學生,它有一個變量String address。如果這個類沒有被實例化,則它的 address 變量也就不存在。而非靜態方法需要訪問非靜態變量,所以對非靜態方法的訪問也是針對某一個具體的對象的方法進行的。對它的訪問一般通過 objectName.methodName(args……) 的方式進行。而靜態成員不依賴於對象存在,即使是類所屬的對象不存在,也可以被訪問,它對整個進程而言是全局的。因此,在靜態方法內部是不可以直接訪問非靜態成員的。
- Code如下:
- import java.io.FileNotFoundException;
- import java.io.IOException;
- import java.io.InputStream;
- import java.util.Properties;
- public class GetProperties {//不用static
- public String getCotent(){//不用static
- String content=”";
- try {
- Properties properties = new Properties();
- InputStream is = getClass().getResourceAsStream(“test.properties”);//ok
- //InputStream is = getClass().getClassLoader().getResourceAsStream(“test.properties”); //ERROR:Exception in thread “main” java.lang.NullPointerException
- properties.load(is);
- is.close();
- content = properties.getProperty(“str1″);
- } catch (FileNotFoundException ex) {
- ex.printStackTrace();
- }catch (IOException ex) {
- ex.printStackTrace();
- }
- return content;
- }
- public static void main(String[] args){
- GetProperties gp = new GetProperties();//實例化
- String s = gp.getCotent();
- System.out.println(s);
- }
- }
- test.properties中內容爲str1=123