Discuss / Java / Cannot make a static reference to the non-static method getClass() from the type Object

Cannot make a static reference to the non-static method getClass() from the type Object

Topic source

同学们难道没有出现类似的错误吗?在main方法里面调用getClass()的时候?

public class Prop {

	public static void main(String[] args) throws FileNotFoundException, IOException {
		
		//read from classpath
		Properties prop1 = new Properties();
		prop1.load(getClass().getResourceAsStream("prop.properties"));
		String filepath = prop1.getProperty("last_open_file");
		String interval = prop1.getProperty("auto_save_interval");
		System.out.println(filepath + interval);
}
}

同样遇到,请问解决这个问题了吗

.getClass()应该是对某个实例的方法,可是这里都没有实例呀

廖雪峰

#3 Created at ... [Delete] [Delete and Lock User]

目的是调用Class.getResourceAsStream()所以先获取Class实例:

如果你有一个实例当然调用 this.getClass().getResourceAsStream()

如果在static方法里没有实例那就用 Prop.class.getResourceAsStream()

学到这了还解决不了基础问题就得回去补补


  • 1

Reply