简体   繁体   English

在Java编译器进行类型检查之前是否已完成类型擦除?

[英]Is type erasure done before the Java compiler does type checking?

Here is a code sample: 这是一个代码示例:

public class TypeErasure<X extends String>{
    private X data;

    public TypeErasure(String s){
        this.data = s;
    }

According to me, after type erasure the code should look like this: 据我说,类型擦除后,代码应如下所示:

public class TypeErasure{
    private String data;

    public TypeErasure(String s){
        this.data = s;
    }

But I get a compile time error saying 但是我收到一个编译时错误消息

Error:(139, 25) java: incompatible types: java.lang.String cannot be converted to X

Once type erasure is done, information about X is lost, so why does the compiler complain? 一旦完成类型擦除,有关X的信息就会丢失,那么为什么编译器会抱怨呢?

Once type erasure is done, information about X is lost, so why does the compiler complain? 一旦完成类型擦除,有关X的信息就会丢失,那么为什么编译器会抱怨呢?

Your observation answers your main question: 您的观察回答了您的主要问题:

Is type erasure done before the Java compiler does type checking? 在Java编译器进行类型检查之前是否已完成类型擦除?

Evidently, the type checking happens before the type is erased, that why you get an error. 显然,类型检查是在擦除类型之前进行的,这就是为什么会出现错误。

You can read more about this in the sub-section of the relevant documentation . 您可以在相关文档的小节中阅读有关此内容的更多信息。

See also this other answer on the topic. 另请参阅主题的其他答案

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

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