简体   繁体   English

Eclipse和Maven之间类型转换的不同编译行为

[英]Different compilation behavior with type cast between eclipse and maven

Here is my code example: 这是我的代码示例:

private static void fac(Map<? extends Serializable,? extends Serializable> mapTo){
    //do sth.
}

public static void main(String[] args) {
    Map<String,Object> mapFrom=null;
    fac((Map<? extends Serializable, ? extends Serializable>) mapFrom);     
}

The code above is compiled successfully in eclipse(with a type safety warning) but failed in maven(an "incompatible types" error caused by javac?). 上面的代码在eclipse中成功编译(带有类型安全警告),但在maven中失败(由javac引起的“不兼容类型”错误?)。

Now I have to change my code like this: 现在,我必须像这样更改代码:

public static void main(String[] args) {
    Map<String,Object> mapFrom=null;
    fac((Map) mapFrom);     
}

I've confirmed the java version is the same, and my question is: 我已经确认Java版本相同,而我的问题是:

  1. Why do they have different behavior? 他们为什么有不同的行为?

  2. What's the preferred way to write the code? 编写代码的首选方式是什么?

Eclipse comes with its own Java compiler; Eclipse带有自己的Java编译器。 Maven uses javac . Maven使用javac Most of the time, both accept the same code but generics are complicated and compiler do have bugs. 大多数情况下,两者都接受相同的代码,但泛型很复杂,并且编译器确实存在错误。 There are a couple of known bugs in javac of Java 6 which cause problems, for example. 例如,Java 6的javac中有几个已知的bug会引起问题。

Oracle will not fix them. Oracle不会修复它们。 The solution is to use Java 7 to run Maven and configure the maven-compiler-plugin the generate Java 6 byte code (see Kumar Sambhav's answer ). 解决方案是使用Java 7运行Maven并配置maven-compiler-plugin以生成Java 6字节代码(请参阅Kumar Sambhav的答案 )。

Try adding this plugin (inside build->plugins-> tag) to your pom.xml :- 尝试将此插件(在build-> plugins->标签内)添加到pom.xml中:

        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.0</version>
            <configuration>
                <source>1.6</source>
                <target>1.6</target>
            </configuration>
        </plugin>

This will ensure the compiler version to be used with your project. 这将确保编译器版本可用于您的项目。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM