Within my project package "pypapo.alphabet" I would like to have one class "alphabetStatic" that contains all frequently used variables (paths, directories, files, constants, etc...) as static final fields throughout the project. In order to not fill up the code of the other classes with the "alphabetStatic"-prefix every time I access one of those static final fields I would like to perform some kind of "import static alphabetStatic". I know that the import static statement refers to the classes of a package. However is it possible to import the fields of a class in such manner?
-
3Unrelated: java class names go UpperCase, always!GhostCat– GhostCat2019-06-21 11:06:16 +00:00Commented Jun 21, 2019 at 11:06
-
Naturally. This ocurred while converting my real project to Stack Overflow suitable fictive names :)pypapo– pypapo2019-06-21 11:12:39 +00:00Commented Jun 21, 2019 at 11:12
3 Answers
I know that the import static statement refers to the classes of a package.
Not really. It refers to static members of a class.
You can use import static with a fullquafiliedclassname.* (to mean any static member of the class) or with specific static field or method of a class.
For example to make an import static of a specific static field or method of a class, this is the syntax :
import static packages.Clazz.fieldOrMethod;
1) static field example
So you could do it to import the static out field form System :
import static java.lang.System.out;
and use it :
out("...");
1) static method example : same syntax.
import static org.junit.jupiter.api.Assertions.assertEquals*;
And use it :
assertEquals(expected, actual);
3) All static members of a class
Just suffix it with a wildcard :
import static org.junit.jupiter.api.Assertions.*;
Comments
Try this:
import static pypapo.alphabet.AlphabetStatic.*;
Note that classe names in Java must start with an uppercase letter.