简体   繁体   English

Java泛型类型的擦除?

[英]Java Generics- type erasure?

If I have a subclass which extends MySuperClass and I have the following generic class: 如果我有一个扩展MySuperClass的子类,并且有以下通用类:

public class GenericClass<M extends MySuperClass>{

    public void aMethod(M m);

}

public class SubClass1 extends MySuperClass{}

then I do: 然后我做:

SubClass1 sc1 = new SubClass1();

GenericClass<MySuperClass> msc = new GenericClass<MySuperClass>();

msc.aMethod(sc1);

is is type erasure which determines whether the parametized type is legal? 类型擦除是确定参数化类型是否合法的吗? I presume the compiler can look at M extends MySuperClass , look at and determine its legal- but I wasnt sure if type erasure handled this? 我认为编译器可以查看M extends MySuperClass ,查看并确定其合法性-但我不确定类型擦除是否可以解决此问题?

Type erasure refers to the fact that the generic type parameters and instantiations are removed after the compilation. 类型擦除是指在编译后删除了通用类型参数和实例化的事实。 The compiler checks the types at compile time and then deletes all the type parameters. 编译器在编译时检查类型,然后删除所有类型参数。

Compiler is the one which make sure about type safety based on generic definition in code. 编译器是一种基于代码中的通用定义确保类型安全的工具。

Type erasure removes them while compilation and 类型擦除会在编译时删除它们,并且

Replace all type parameters in generic types with their bounds or Object if the type parameters are unbounded 如果类型参数不受限制,请将通用类型中的所有类型参数替换为其边界或对象

.

Type-safety is something that is ensured by the compiler. 类型安全是由编译器确保的。 The only job of the type erasure is to erase the generics portion to make the code backwards compatible with the legacy codes which were written before the generics showed up in Java. 类型擦除的唯一工作是擦除泛型部分,以使代码向后兼容在Java中出现泛型之前编写的遗留代码。 So, it's the compiler that makes sure your code is syntactically correct whether it's relation to generics or not, before the erasure comes into action. 因此,在删除操作生效之前,由编译器确保您的代码在语法上正确无误,无论它是否与泛型相关。

Type erasure is a runtime artefact, when all classes are effectively "raw" (untyped). 当所有类都有效地“原始”(未键入类型擦除运行时的产物。

Generics exist only during compilation. 泛型仅在编译期间存在。 The compiler checks that the generic parameter is within bounds, but the compiled bytecode has no type information. 编译器检查泛型参数是否在范围之内,但是编译后的字节码没有类型信息。

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

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