打开枚举时Maven编译失败

dka*_*ros 5 java maven-3 maven-compiler-plugin

我是一个mavenifying(是一个单词?)一个项目,其构建过程到目前为止完全基于ant/shell脚本.

请考虑以下枚举

public enum ResourceType {
    A, B;
}
Run Code Online (Sandbox Code Playgroud)

以下bean:

public ResourceTypeOwner {
    //set get resourceType property
}
Run Code Online (Sandbox Code Playgroud)

以下代码片段:

void foo(ResourceTypeOwner rto) {
    ResourceType resourceType = rto.getResourceType();
    switch (resourceType) {
    case A:
        handleA(resourceType); break;
    case B:
        handleB(resourceType); break;
    default:
        throw new RuntimeException("Unsupported resource type");
    }
}
Run Code Online (Sandbox Code Playgroud)

使用maven构建时出现编译错误:

无法打开ResourceType类型的值.只允许使用可转换的int值或枚举变量

pom.xml具有以下用于编译的插件配置

<plugins>
    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.0</version>
        <configuration>
            <compilerId>eclipse</compilerId>
            <compilerVersion>1.6</compilerVersion>
            <source>1.6</source>
            <target>1.6</target>
        </configuration>
        <dependencies>
            <dependency>
                <groupId>org.codehaus.plexus</groupId>
                <artifactId>plexus-compiler-eclipse</artifactId>
                <version>2.2</version>
            </dependency>
        </dependencies>
    </plugin>
...
</plugins>
Run Code Online (Sandbox Code Playgroud)

ant(与org.eclipse.jdt.core.JDTCompilerAdapter)和eclipse构建/编译都很好.我显然做错了(除非它是一个未报告的maven-compiler-plugin或plexus-compiler-eclipse插件bug,这有点不太可能,切换枚举既不坏也不是火箭科学).有人有想法吗?

其他环境细节

$ mvn -version Apache Maven 3.0.4(r1232337; 2012-01-17 10:44:56 + 0200)Maven home:/home/d/dev/tools/apache-maven-3.0.4 Java版本:1.6.0_35 ,供应商:Sun Microsystems Inc. Java主页:/opt/jdk1.6.0_35/jre默认语言环境:en_US,平台编码:UTF-8操作系统名称:"linux",版本:"3.2.0-40-generic",arch :"amd64",家庭:"unix"

更新:

标准JDK编译器成功编译特定类.看起来像一个plexus-compiler-eclipse 2.2问题.

Ken*_*ney 4

我能够重现并发现问题。

事实证明,需要将设置org.eclipse.jdt.core.compiler.compliance设置为目标版本才能使其能够识别java.lang.Enum

当同时设置targetVersionAND时,此设置仅由 plexus-compiler-eclipse 设置。optimize[1]

像这样修改你的pom,它应该可以工作:

<plugins>
  <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.1</version> <!-- or 3.0 -->
    <configuration>
        <compilerId>eclipse</compilerId>
        <source>1.6</source>
        <target>1.6</target>
        <optimize>true</optimize>   <!-- add this line! -->
Run Code Online (Sandbox Code Playgroud)

我不确定为什么 plexus-compiler-eclipse 决定优化会影响合规性级别,所以这实际上是一种解决方法。

此外,此代码足以触发该问题:

class Foo {
    static enum MyEnum { A }

    void foo() {
        switch ( MyEnum.A ) { case A: }
    }
}
Run Code Online (Sandbox Code Playgroud)

[1] https://github.com/sonatype/plexus-compiler/blob/master/plexus-compilers/plexus-compiler-eclipse/src/main/java/org/codehaus/plexus/compiler/eclipse/EclipseJavaCompiler.java #L156