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  
原文地址:https://www.cnblogs.com/lechance/p/4373201.html