Static import vs wildcard

4013 views java
0

I was wondering if it is possible in Java to use static import with wildcards?

e.g.:

import static java.util.Arrays.*;

answered question

Why not try it?

2 Answers

1

yes that is possible.

Static imports are for importing static members of classes. Just like regular imports, you can use a wildcard or import a specific member.

example

import static java.util.Arrays.asList; // importing static member asList
import static java.util.Arrays.* ; // importing all static members of Arrays class

posted this
7

You can. The import static will import all static members from the class. For example with Math:

import static java.lang.Math.*; // Imports all static members from Math

boolean isSmaller = E < PI;

If you didn't do this you would have to write:

boolean isSmaller = Math.E < Math.PI;

You should use static imports rarely though, as they tend to make your code harder to read. For a constants class it's okay to do it, if you use the constants a lot, but don't overuse it!

posted this

Have an answer?

JD

Please login first before posting an answer.