Reputation: 53
So I'm facing a cannot find symbol error when static importing an enum in a class that depends on it. They are both in separate files within the same directory. I've omitted an explicit package name.
TokenType.java
// No imports
enum TokenType {
ADD, MINUS, MULTIPLY, DIVIDE,
...
}
Scanner.java
import java.util.ArrayList;
import java.util.List;
import java.util.HashMap;
import java.util.Map;
import static TokenType.*; // <--- (error: cannot find symbol)
class Scanner {
private static final Map <String, TokenType> keywords; // <--- (no error; javac can resolve the class name just fine)
static {
keywords = new HashMap<>();
keywords.put("+", ADD); // <-- (error: cannot find symbol, which makes sense)
keywords.put("-", MINUS);
...
}
...
}
I'm just not sure how to proceed. The names are all typed correctly, and there is only one TokenType class so there isn't a class conflict. My other classes in the project directory have no nested classes, do not extend/implement from other classes, or import libraries that have a TokenType class in their dependencies. I've cleaned my directory of all stale classes before each compile, and even changed the order in which I'm calling javac. Any help would be wonderful, thank you.
EDIT: Solution was to put them in a named package. Java doesn't allow imports from default package.
Upvotes: 4
Views: 965
Reputation: 271625
From the fact that the compiler can resolve the simple name TokenType
in Map <String, TokenType>
, it seems like TokenType
is declared in the same package as Scanner
.
You also said that you "omitted an explicit package name", which implies that both of these classes are not declared in the default package (static imports are not possible if they are in the default package), but some package with a name. Let's suppose that both of them are in
package com.example.foo;
Then you need to do:
import static com.example.foo.TokenType.*;
Note that even if you are in a location where the type is accessible with its simple name, you still need to use its canonical name (basically with the package name fully written out) in a static import declaration., and the name has to be qualified (in the form of X.Y
), which is why classes in the default package don't work.
Upvotes: 2