[英]Non-static variable this cannot be referenced from a static context JFrame
[英]Non-static variable filepath cannot be referenced from a static context
我有一个简单的Java程序,如下所示:
public class HelloWorldPrinter {
String filepath;
public void setPath(String path){
this.filepath = path;
}
public static void main(String[] args) throws PrintException, IOException {
FileInputStream in = new FileInputStream(new File(filepath));
}
}
我收到以下错误:
HelloWorldPrinter.java:40:错误:无法从静态上下文引用非静态变量文件路径
FileInputStream in = new FileInputStream(new File(filepath));
我怎样才能解决这个问题?
一种选择是创建HelloWorldPrinter
的实例:
public static void main(String[] args) throws PrintException, IOException {
HelloWorldPrinter printer = new HelloWorldPrinter();
printer.setPath("path/to/file");
FileInputStream in = new FileInputStream(new File(printer.getPath()));
}
您永远无法访问静态字段内的非静态字段。
因为静态字段不需要对象,而非静态字段则需要对象,所以静态字段永远不会知道非静态字段的状态。
因此,您有两种选择,宁可make your field static
,也create an object before accessing it
。
HelloWorldPrinter obj= new HelloWorldPrinter();
FileInputStream in = new FileInputStream(new File(obj.getPath()));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.