简体   繁体   English

为什么此Java代码在一个Eclipse项目中而不在另一个Eclipse项目中生成错误?

[英]Why does this Java code generate an error in one Eclipse project but not the other?

I have the following test class in a file named Sandbox.java : 我在名为Sandbox.java的文件中具有以下测试类:

package cas;

public final class Sandbox {

    public static void main(String[] args) {
        int primitive = 42;
        Integer boxed = primitive;
    }

}

This is something I would expect to work because of autoboxing. 由于自动装箱,这是我希望可以使用的功能。 However, it failed to compile with the error: "Type mismatch: cannot convert from int to Integer". 但是,它无法编译并显示以下错误:“类型不匹配:无法从int转换为Integer”。 To isolate the test case, I put the file in a different Eclipse project, where the code is exactly identical except that package cas; 为了隔离测试用例,我将文件放在另一个Eclipse项目中,除了package cas;之外,代码完全相同package cas; is replaced with package sandbox . package sandbox代替。 In this project, it compiled normally. 在这个项目中,它可以正常编译。

I am using compiler compliance level 1.8, with what I believe is the most up to date JDK. 我使用的编译器符合性级别为1.8,我认为是最新的JDK。 Since autoboxing was introduced in 1.5 if I recall correctly, there shouldn't be any issues with int –> Integer conversion, or so I thought. 如果我没记错的话,由于自动装箱是在1.5中引入的,因此int –> Integer conversion应该不会有任何问题,所以我想。

I checked the Properties for both projects, and every page with the "Enable project specific settings" checkbox has it disabled. 我检查了两个项目的属性,并且每个带有“启用项目特定设置”复选框的页面都将其禁用。 So there should be no difference between the two projects' compilation, no? 因此,两个项目的编译之间应该没有区别,不是吗?

I don't understand why this code would ever give an error in a Java 1.8 environment. 我不明白为什么这段代码在Java 1.8环境中会给出错误。

It turned out that package cas declared a type cas.Integer . 事实证明, package cas声明了cas.Integer类型。 Since names declared in the local package shadow implicitly imported system types, cas.Integer was used in the declaration implicitly instead of java.lang.Integer , and the error message did not give a fully qualified type name. 由于在本地包中声明的名称会隐式导入系统类型, cas.Integer在声明中隐式使用了cas.Integer而不是java.lang.Integer ,并且错误消息未提供完全限定的类型名称。

This problem can be resolved by declaring the variable java.lang.Integer boxed = primitive or (my personal favorite) adding import java.lang.Integer , because specifically imported types shadow implicitly imported package types (which respectively shadow implicitly imported system types). 可以通过声明变量java.lang.Integer boxed = primitive或(添加我个人最喜欢的)添加import java.lang.Integer来解决此问题,因为专门导入的类型会隐式导入的包类型(分别是隐式导入的系统类型)。 Or by not declaring a class named Integer . 或者不声明一个名为Integer的类。 (Although in this case there was a good reason.) (尽管在这种情况下有充分的理由。)

This was, of course, a silly error, but it might be enlightening to someone (seeing as how the error message seemed impossible). 当然,这是一个愚蠢的错误,但是可能对某人有所启发(看似错误消息似乎是不可能的)。

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

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