DEV-NOTES|Java: Surprising import findings

You might not know that the order of static imports and ordinary imports is crucial. I stumbled upon a code snippet using a static import from a static inner class, during some codes research for a work project. Trying out that code ends up with a compiler error, saying that a standard class from the JDK was not found.

For the sake of simplicity and to ease understanding I provide a similar small example to illustrate the issue:

<br />
package de.mindcrimeilab.strange.staticimport;</p>
<p>// this does not work using JDK 8, but in JDK 9 and 10, comment this<br />
// and uncomment the corresponding import below to make it work<br />
// in JDK 8<br />
import static de.mindcrimeilab.strange.staticimport.StrangeIntSorter.FlexibleIntegerComparator.DESC;</p>
<p>import java.util.Collections;<br />
import java.util.Comparator;<br />
import java.util.List;<br />
import java.util.Random;<br />
import java.util.StringJoiner;<br />
import java.util.stream.Collectors;</p>
<p>// uncomment this to make it work with JDK 8<br />
//import static de.mindcrimeilab.strange.staticimport.StrangeIntSorter.FlexibleIntegerComparator.DESC;</p>
<p>/**<br />
 *<br />
 * @author Michael Engelhardt &lt;me@mindcrime-ilab.de&gt;<br />
 *<br />
 */<br />
public class StrangeIntSorter {</p>
<p>	/**<br />
	 * Sort a list of random integers.<br />
	 *<br />
	 * @param {@code FlexibleIntegerComparator.DESC} sort in descending order,<br />
	 *        {@code FlexibleIntegerComparator.ASC} sort in ascending order<br />
	 * @return sorted list<br />
	 */<br />
	public List&lt;Integer&gt; sortRandomIntList(int order) {<br />
		List&lt;Integer&gt; intList = new Random().ints(0, 1024).limit(10).boxed().collect(Collectors.toList());<br />
		Collections.sort(intList, new FlexibleIntegerComparator(order));<br />
		return intList;<br />
	}</p>
<p>	/**<br />
	 * Simple comparator implementation letting you choose the sorting order during<br />
	 * creation.<br />
	 *<br />
	 * @author Michael Engelhardt &lt;me@mindcrime-ilab.de&gt;<br />
	 *<br />
	 */<br />
	static class FlexibleIntegerComparator implements Comparator&lt;Integer&gt; {<br />
		static final int ASC = 1;<br />
		static final int DESC = -1;</p>
<p>		private final int order;</p>
<p>		FlexibleIntegerComparator(int order) {<br />
			this.order = order;<br />
		}</p>
<p>		@Override<br />
		public int compare(Integer o1, Integer o2) {<br />
			return o1.compareTo(o2) * order;<br />
		}<br />
	}</p>
<p>	/**<br />
	 * Main method.<br />
	 *<br />
	 * @param args<br />
	 */<br />
	public static void main(String... args) {<br />
		System.out.println(&quot;Sorting some ints: &quot;);<br />
		StrangeIntSorter strangeIntSorter = new StrangeIntSorter();<br />
		List&lt;Integer&gt; sortedRandomIntList = strangeIntSorter.sortRandomIntList(DESC);</p>
<p>		StringJoiner joiner = new StringJoiner(&quot;,&quot;);<br />
		sortedRandomIntList.forEach(num -&gt; joiner.add(num.toString()));</p>
<p>		System.out.println(joiner.toString());<br />
	}<br />
}<br />

On Java 8 you will get a compiler error:

:45: error: cannot find symbol
        static class FlexibleIntegerComparator implements Comparator<Integer> {
                                                          ^
  symbol:   class Comparator
  location: class StrangeIntSorter

That is very surprising, because that is one of the standard interfaces provided by the Java SDK. Curiously it will work if you run it from inside Eclipse. More over Eclipse puts that static import on top of the class if you use the ‚organize imports‘ option. You can fix this error by putting the static import statement below the non-static import statements.

According to the Java Language Specification JLS 7.5 Import Declarations the order of static and non static imports could be mixed. A compilation unit consists beside others out of a number of ImportDeclarations JLS 7.3:

CompilationUnit:
    PackageDeclarationopt ImportDeclarationsopt TypeDeclarationsopt

ImportDeclarations:
    ImportDeclaration
    ImportDeclarations ImportDeclaration

TypeDeclarations:
    TypeDeclaration
    TypeDeclarations TypeDeclaration

Whereas each ImportDeclaration might be either an import or a static import JLS 7.5:

ImportDeclaration:
    SingleTypeImportDeclaration
    TypeImportOnDemandDeclaration
    SingleStaticImportDeclaration
    StaticImportOnDemandDeclaration

Thankfully that problem is solved by later versions of the JDK. On JDK 9 as well as on JDK 10 the code compiles without any errors regardless if you are putting the static imports on top or below. To take it the right way it does depend on the position of the static import that way, that you have to import all necessary symbols to compile the originating class of the static import.

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert.

3 + 10 =