我遇到的情况是,当我按照特定顺序指定源时,某些Java 1.6源代码不能在Maven中编译,只能在javac中编译。
pom.xml很简单但指定-source
和-target
为1.6:
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
</plugins>
</build>
ComputeOperation.java
package test.domain;
public interface ComputeOperation<T> {
public T compute(T arg1, T arg2);
}
Computations.java
package test.domain;
public enum Computations implements ComputeOperation<Integer> {
ADD {
@Override
public Integer compute(Integer arg1, Integer arg2) {
return arg1 + arg2;
}
},
SUBTRACT {
@Override
public Integer compute(Integer arg1, Integer arg2) {
return arg1 - arg2;
}
}
}
App.java
package test.app;
import test.domain.*;
public class App {
public static void main( String[] args ) {
System.out.println(Computations.ADD.compute(1, 1));
}
}
Maven构建失败如下(full debug log here):
[ERROR] COMPILATION ERROR :
[INFO] -------------------------------------------------------------
[ERROR] /home/nzucker/projects/maven-test/src/main/java/test/app/App.java:[7,44] cannot find symbol
symbol : method compute(int,int)
location: class test.domain.Computations
[INFO] 1 error
如果App.java出现在Computations.java之前,普通的旧javac
编译失败成功:
[nzucker:maven-test]$ javac -source 1.6 -target 1.6 -g -d target/classes src/main/java/test/app/App.java src/main/java/test/domain/Computations.java src/main/java/test/domain/ComputeOperation.java
src/main/java/test/app/App.java:7: cannot find symbol
symbol : method compute(int,int)
location: class test.domain.Computations
System.out.println(Computations.ADD.compute(1, 1));
^
1 error
但如果我将App.java放在输入源中,那么构建会成功:
[nzucker:maven-test]$ javac -source 1.6 -target 1.6 -g -d target/classes src/main/java/test/domain/Computations.java src/main/java/test/domain/ComputeOperation.java src/main/java/test/app/App.java
[nzucker:maven-test]$ java -cp target/classes/ test.app.App
2
最后,如果我将App.java中的import
更改为静态导入,则编译成功:
package test.app;
import static test.domain.Computations.*;
public class App {
public static void main( String[] args ) {
System.out.println(ADD.compute(1, 1));
}
}
问题:
我知道“Workaround for javac compilation order bug in maven” - 所以我的问题是为什么会发生这种情况?这是Maven的真正缺陷吗?如果是这样,那么JIRA问题是什么?
另外,为什么编译失败?我认为javac在预处理阶段解决了类之间的依赖关系和编译顺序?我猜我错了?是否有规范涵盖这一点?
好的,我链接的另一个问题有一个响应,指出Java 1.6中的错误。答案是升级到Java 1.7或实现解决方法。