5

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?

2
  • 3
    Unrelated: java class names go UpperCase, always! Commented Jun 21, 2019 at 11:06
  • Naturally. This ocurred while converting my real project to Stack Overflow suitable fictive names :) Commented Jun 21, 2019 at 11:12

3 Answers 3

2

Nothing prevents you from importing package X from inside package X.

So

import static status pypapo.alphabet.alphabetStatic.*;

should definitely work for you.

Sign up to request clarification or add additional context in comments.

Comments

2

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

0

Try this:

import static pypapo.alphabet.AlphabetStatic.*;

Note that classe names in Java must start with an uppercase letter.

1 Comment

Thanks for the quick answer. In fact I forgot to add the package statement to the Alphabet class itself, which thwarted this attempt earlier.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.