在java泛型中键入Witness [英] Type Witness in java generics

查看:83
本文介绍了在java泛型中键入Witness的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  BoxDemo。< Integer> addBox( Integer.valueOf(10),listOfIntegerBoxes); 




或者,如果您省略类型见证,则Java编译器
自动推断(从方法的参数)类型
参数是整数:



  BoxDemo.addBox(Integer.valueOf(20),listOfIntegerBoxes); 

想要了解


  • 做这件事的正确方法是什么?使用类型见证或让Java推断?

  • 是否存在绝对需要使用类型见证的情况?

  • 这是Java 5的一项功能还是以后再添加?


解决方案




做这件事的正确方法是什么?使用类型见证或让Java推断?


没有技术上正确的答案,因为这两种方法都是有效的。但代码可读性应始终是质量标准。所以后者更好。另外,你可能会在开发的后期改变参数的类型。







p>是否存在绝对需要使用类型见证的情况?


是的。当无法从输入参数推断到方法时,需要它。也许泛型类型仅用于返回值,与参数类型无关。然后您只需指定它。







这是Java 5的一项功能还是稍后添加的功能?


泛型是Java 5中的一种语言功能。类型推断是在JLS中指定的编译器功能。在 Java 8 JLS 中,该主题获得了自己的章节。每个Java版本都在该功能中做了一些增强。例如Java 7引入了钻石运算符。就我所知,已经在Java 5中引入了方法的类型见证。


I understand what Type Witness is as I see from Generics Trail In Java Documentation

BoxDemo.<Integer>addBox(Integer.valueOf(10), listOfIntegerBoxes);

Alternatively, if you omit the type witness,a Java compiler automatically infers (from the method's arguments) that the type parameter is Integer:

BoxDemo.addBox(Integer.valueOf(20), listOfIntegerBoxes);

Would like to understand

  • What is the right way to do this? Using Type Witness or let Java infer?
  • Is there a case where using type witness is absolutely needed?
  • Is this a feature from Java 5 or added later?

解决方案

Some quick answers to your questions:

What is the right way to do this? Using Type Witness or let Java infer?

There is no technical correct answer for this as both approaches are valid. But code readability should always be the quality criterion. So the latter is better. Additionally you might change the type of your arguments at a later point in development. With type inference you do not have to change that line.


Is there a case where using type witness is absolutely needed?

Yes. It is needed when type cannot be inferred from the input arguments to a method. Maybe the generic type is only used for the return value, indipendently from the types of the arguments. Then you simply must specify it.


Is this a feature from Java 5 or added later?

Generics are a language feature from Java 5 on. Type inference is a compiler feature that is specified in the JLS. In the Java 8 JLS this topic got an own chapter. Each Java version did some enhancements in that feature. For example Java 7 introduced the diamond operator. Type witness for methods was already introduced in Java 5 as far as I know.

这篇关于在java泛型中键入Witness的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆