Cannot make a static reference to the non-static method的解決方法

  • 報錯原因:在一個類中寫了一個public String getContent()方法和一個main()方法,getContent()方法中包含了getClass()方法,在main()方法中直接調用了getContent()就出現如題的錯誤。這樣一樣
  • 解決方法:先實例化類,然後再調用getContent()就沒有問題了
  • [java] view plaincopy
    1. GetProperties gp = new GetProperties();  
    2. String s = gp.getCotent();  
    這樣一來都不要加static了
  • 說明:在靜態方法中,不能直接訪問非靜態成員(包括方法和變量)。因爲,非靜態的變量是依賴於對象存在的,對象必須實例化之後,它的變量纔會在內存中存在。例如一個類 Student 表示學生,它有一個變量String address。如果這個類沒有被實例化,則它的 address 變量也就不存在。而非靜態方法需要訪問非靜態變量,所以對非靜態方法的訪問也是針對某一個具體的對象的方法進行的。對它的訪問一般通過 objectName.methodName(args……) 的方式進行。而靜態成員不依賴於對象存在,即使是類所屬的對象不存在,也可以被訪問,它對整個進程而言是全局的。因此,在靜態方法內部是不可以直接訪問非靜態成員的。
  • Code如下:

[java] view plaincopy
  1. import java.io.FileNotFoundException;  
  2. import java.io.IOException;  
  3. import java.io.InputStream;  
  4. import java.util.Properties;  
  5.   
  6. public class GetProperties {//不用static  
  7. public String getCotent(){//不用static  
  8. String content=”";  
  9.   
  10. try {  
  11. Properties properties = new Properties();  
  12.   
  13. InputStream is = getClass().getResourceAsStream(“test.properties”);//ok  
  14. //InputStream is = getClass().getClassLoader().getResourceAsStream(“test.properties”); //ERROR:Exception in thread “main” java.lang.NullPointerException  
  15.   
  16. properties.load(is);  
  17. is.close();  
  18.   
  19. content = properties.getProperty(“str1″);  
  20.   
  21. catch (FileNotFoundException ex) {  
  22. ex.printStackTrace();  
  23. }catch (IOException ex) {  
  24. ex.printStackTrace();  
  25. }  
  26. return content;  
  27. }  
  28.   
  29. public static void main(String[] args){  
  30. GetProperties gp = new GetProperties();//實例化  
  31. String s = gp.getCotent();  
  32.   
  33. System.out.println(s);  
  34. }  
  35. }  
  36.   
  37. test.properties中內容爲str1=123  

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章