我试图通过在System.out.println()
内定义静态方法来缩短Util.java
。我想利用Util.print()进一步缩短为print()
。所以我做了静态导入。
Util.java与ListOfNumbers.java位于同一目录下。当我尝试从测试器类访问writeList()时,我得到以下错误:
import java.io.*;
import java.util.List;
import java.util.ArrayList;
import static Util;
public class ListOfNumbers {
...
...
public void writeList() {
// The FileWriter constructor throws IOException, which must be caught.
PrintWriter out = null;
try {
print("Entered try statement...");
...
} catch (IOException | IndexOutOfBoundsException e){
print("Exception thrown: \n" + e.getMessage());
...
}
}
}
错误:
>> javac Tester.java && java Tester
.\ListOfNumbers.java:4: error: '.' expected
import static Util;
^
.\ListOfNumbers.java:4: error: ';' expected
import static Util;
^
.\ListOfNumbers.java:4: error: cannot find symbol
import static Util;
^
symbol: class Util
.\ListOfNumbers.java:4: error: static import only from classes and interfaces
import static Util;
^
.\ListOfNumbers.java:24: error: cannot find symbol
print("Entered try statement...");
^
symbol: method print(String)
location: class ListOfNumbers
.\ListOfNumbers.java:34: error: cannot find symbol
print("Exception thrown: \n" + e.getMessage());
^
symbol: method print(String)
location: class ListOfNumbers
6 errors
答案 0 :(得分:2)
您应该导入方法名称
import static Util.print;
如果要从Util导入所有静态方法:
import static Util.*;
答案 1 :(得分:1)
以下答案帮助我克服了这个问题!猜猜这一定是个bug。