static import only from classes and interfaces

2019-06-15 07:34发布

问题:

My code compiles fine in Eclipse, but when I try to compile from the commandline (via our ruby-based buildr system), I get this error message:

static import only from classes and interfaces

Suggesting that static import of public static fields is not permitted. What should I look for to help diagnose this problem? How can I fix it?

Update: per @Ted's request, the constant declaration in the referenced file:

public static final String NULL = "<NULL>";

and the (bowdlerized) reference in the referring file:

import static my.path.MyClass.NULL;

回答1:

My guess is that Eclipse and buildr are using either different Java compiler versions or different compiler flags. There's a bug in the Java 7 compiler (bug ID: 715906) that generates this error when you statically import specific fields. The work-around is to use a wildcard static import. So instead of:

import static package.Class.staticField;

do this:

import static package.Class.*;


回答2:

Late answer but I just got a similar issue and figured it out. I'll post in case it helps anyone else who finds this page...

I got a similar error when, after a big merge and refactor, I accidentally put a test class into src/main/java instead of src/test/java. Since the JUnit dependency was scope=tests, it didn't work in pure maven. Maybe you are having the same issue



回答3:

I also had this error and my issue turned out to be a wayward static import of a junit 4 package in my test source file.

I had the following:

import static org.junit.Assert.fail;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTimeout;

I removed the import static org.junit.Assert.fail; (no idea how I managed to get that in there in the first place) and all is now working.



回答4:

I accidentally set test directory as source. And Test sources were considered as source files.

sourceSets.main.java.srcDirs 'src'

| -- src
  | -- main
  | -- test

Fix:

sourceSets.main.java.srcDirs 'src/main'