简体   繁体   English

Java-类型擦除和类型推断之间有什么区别?

[英]Java - What's the difference between type erasure and type inference?

What's the difference between type erasure and type inference? 类型擦除和类型推断有什么区别? Are they both compile-time operations? 它们都是编译时操作吗?

Type Erasure : which removes the generic type information at compile time process. Type Erasure在编译时删除通用类型信息。

  • Example: Box<String> is translated to type Box , which is called the raw type. 示例: Box<String>转换为Box类型,称为原始类型。

How Type Inference is different from type Erasure? 类型推断与类型擦除有何不同?
Before JDK 7: 在JDK 7之前:

Box<String> box=new Box<String>();

From JDK 7: 从JDK 7:

 Box<String> box=new Box<>();

My guess the above examples are Type Inference. 我猜上面的例子是类型推断。 Is that right? 那正确吗?

Is Type Inference is opposite to Type Erasure ? Type InferenceType Erasure相反吗?

Both of them serve completely different needs: 两者都满足完全不同的需求:

Type erasure is like you said and is needed because java byte code is not generic hence you need to remove the typing. 类型擦除就像您说的那样是必需的,因为Java字节码不是通用的,因此您需要删除类型。 This isn't a feature that helps you code it's just an automatic compile time change that has to happen for the jvm to understand your code. 这不是帮助您编写代码的功能,只是jvm理解您的代码而必须进行的自动编译时更改。

Type inference on the other hand is the compiler being "smart" and knowing what type you were referring to even though you didn't actually write it. 另一方面,类型推断是编译器“很聪明”,并且即使您实际上没有编写代码,也知道要引用的类型。 Just like in your example the compiler knows that Box<>() actually means Box<String>() and lets you continue coding with type safety as if you wrote Box<String> . 就像在您的示例中一样,编译器知道Box<>()实际上是Box<String>()并让您像写Box<String>一样继续使用类型安全进行编码。 This way you can write less verbose code and the compiler would still understand it. 这样,您可以编写更少的冗长代码,并且编译器仍然可以理解它。

You can understand from all of this that generics in Java are actually mostly a compile time thing that lets you code with more safety and helps you find errors in compile-time rather than run-time. 您可以从所有这些内容中了解到,Java中的泛型实际上主要是编译时的东西,它使您可以更安全地进行编码,并帮助您在编译时而不是运行时发现错误。

They are both compile-time operations. 它们都是编译时操作。

Type erasure is translation from generic Java source code back into regular Java code (removes T , A and any other paramterized types). 类型擦除是将通用Java源代码转换回常规Java代码(删除TA和任何其他参数化类型)。

Type inference can happen when a generic method is invoked or when a generic type object is created. 当调用泛型方法或创建泛型类型对象时,可能会发生类型推断。 For example, if you 例如,如果您

class Box<T> {
    ...
}

Then when you write 然后当你写

Box<String> box = new Box<>();
// type parameter inferred

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

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