您的位置:首页 > Web前端

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

2016-01-12 10:42 465 查看
报错原因:在一个类中写了一个public String getContent()方法和一个main()方法,getContent()方法中包含了getClass()方法,在main()方法中直接调用了getContent()就出现如题的错误。这样一样

解决方法:先实例化类,然后再调用getContent()就没有问题了

GetProperties gp = new GetProperties();
String s = gp.getCotent();


这样一来都不要加static了

说明:在静态方法中,不能直接访问非静态成员(包括方法和变量)。因为,非静态的变量是依赖于对象存在的,对象必须实例化之后,它的变量才会在内存中存在。例如一个类 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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: