Order of imports seems to matter for compilation to succeed?

我怕爱的太早我们不能终老 提交于 2019-12-11 07:40:08

问题


I'm writing a unit test for some Java class in Eclipse. I always let Eclipse handle my imports automatically, and it orders them according to whatever default scheme.

Now, I have the following situation. The unit test builds and runs just fine in Eclipse. However, when I build the tests on the command line (using some Ant targets), javac complains that it can't find one of the classes I've imported. Since I'm testing something with caching, the relevant bits of the test file (Test.java let's say) are:

import com.abc.my.stuff.MyCacheLoader.Operation;
import com.google.common.cache.CacheLoader;

public class Test {
 ... test code, such as ...

     List<MyKey> recordedKeys = dummyLoader.getKeysFor(Operation.LoadAll);

}

// Dummy cache loader which just records the keys
class MyCacheLoader extends CacheLoader<MyKey, MyValue> {
   enum Operation { Load, LoadAll }

   @Override
   public MyValue load(MyKey key) throws Exception { .... whatever .... }

   @Override
   public MyValue loadAll(Iterable<MyKey> key) throws Exception { .... whatever .... }

   public List<MyKey> getKeysFor(Operation op) { ... impl ... }
}

Notice that the import for my local class's inner enum appears before the import for the Guava CacheLoader class, because they are ordered alphabetically. When I try to compile this using Ant on the command line, javac can't find 'CacheLoader'. When I switch the order of the imports, the build succeeds (whereas Eclipse doesn't care either way).

I'm mystified as to what's going on here.


回答1:


Apparently, the compiler in Eclipse doesn't have the following Sun bug:

http://bugs.java.com/bugdatabase/view_bug.do?bug_id=6391197

which I found via:

http://unimplemented.blogspot.com/2007/08/my-java-puzzle-does-order-of-import.html

This explains why flipping the order of imports makes no difference to Eclipse, but it does to the Sun compiler. Part of the problem is fixed in Java 8, but my particular manifestation is targeted for a fix in Java 9: http://bugs.java.com/bugdatabase/view_bug.do?bug_id=7101822



来源:https://stackoverflow.com/questions/26520832/order-of-imports-seems-to-matter-for-compilation-to-succeed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!