$ javac TestFilter.java
TestFilter.java:19: non-static variable this cannot be referenced from a static context
for(File f : file.listFiles(this.filterFiles)){
^
1 error
$ sed -i '[email protected]@[email protected]' TestFilter.java
$ javac TestFilter.java
$ java TestFilter
file1
file2
file3
TestFilter.java的Java:靜態非靜態,這個問題
import java.io.*;
import java.util.*;
public class TestFilter {
private static final FileFilter filterFiles;
// STATIC!
static{
filterFiles = new FileFilter() {
// Not Static below. When static, an error:
// "accept(java.io.File) in cannot implement
// accept(java.io.File) in java.io.FileFilter;
// overriding method is static"
//
// I tried to solve by the change the problem at the bottom.
public boolean accept(File file) {
return file.isFile();
}
};
}
// STATIC!
public static void main(String[] args){
HashSet<File> files = new HashSet<File>();
File file = new File(".");
// IT DID NOT WORK WITH "This" but with "TestFilter".
// Why do I get the error with "This" but not with "TestFilter"?
for(File f : file.listFiles(TestFilter.filterFiles)){
System.out.println(f.getName());
files.add(f);
}
}
}
更新:界定 「當前對象」
構造函數創建,創建對象,但該this
確實不是指當前對象「測試」。它適用於我將此更改爲「測試」但它不適用於「此」。爲什麼?
$ javac TestFilter.java
TestFilter.java:28: non-static variable this cannot be referenced from a static context
for(File f : this.getFiles()){
^
1 error
$ cat TestFilter.java
import java.io.*;
import java.util.*;
public class TestFilter {
private static final FileFilter filterFiles;
private HashSet<File> files;
static{
filterFiles = new FileFilter() {
public boolean accept(File file) {
return file.isFile();
}
};
}
TestFilter(){
files = new HashSet<File>();
File file = new File(".");
for(File f : file.listFiles(filterFiles)){
files.add(f);
}
}
public static void main(String[] args){
// CONSTRUCTOR with no pars invoked and object "test" created here!
TestFilter test = new TestFilter();
// Why does it not work with "this"?
// "test" is surely the current object.
for(File f : this.getFiles()){
System.out.println(f.getName());
}
}
public HashSet<File> getFiles() { return files; }
}
引用'Update:define'當前對象'':「this」只存在於「內部」實例(非靜態)方法中。在實例方法之外,您必須通過外部變量「test」引用實例。 – 2010-04-12 20:47:22