2016-03-29 5 views
2

から参照することはできません、次のように私は、単純な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: error: non-static variable filepath cannot be referenced from a static context

FileInputStream in = new FileInputStream(new File(filepath));

が、私はこれをどのように修正することができます?

答えて

3

1つのオプションは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())); 
} 
1

あなたは、静的フィールド内の非静的フィールドにアクセスすることはできません。

静的フィールドはオブジェクトを必要とせず、非静的なので、静的フィールドは非静的フィールドの状態を決して知らないためです。

だから、make your field staticまたはcreate an object before accessing itの2つのオプションがあります。

HelloWorldPrinter obj= new HelloWorldPrinter(); 
FileInputStream in = new FileInputStream(new File(obj.getPath()));