什么是包装器类? 这样的类有什么用处呢?


当前回答

包装类是一个“包装”其他东西的类,就像它的名字一样。

它更正式的定义是实现适配器模式的类。这允许您将一组api修改为更可用、更可读的形式。例如,在c#中,如果你想使用本机Windows API,它有助于将它包装成一个符合. net设计准则的类。

其他回答

包装器类是一个包装另一个类并提供客户端和被包装的原始类之间的抽象的类。

In general, a wrapper class is any class which "wraps" or "encapsulates" the functionality of another class or component. These are useful by providing a level of abstraction from the implementation of the underlying class or component; for example, wrapper classes that wrap COM components can manage the process of invoking the COM component without bothering the calling code with it. They can also simplify the use of the underlying object by reducing the number interface points involved; frequently, this makes for more secure use of underlying components.

包装器类的出现是为了满足程序员的基本需求——即在只允许使用object的地方使用原始值。顾名思义,包装器类包装一个基本值,并将该值保存在Object中。因此,在所有不允许使用原语的地方——比如泛型、hashmap-key、数组列表等——程序员现在可以选择提供这些原语值作为相应的包装器类型。

此外,这些包装器类型有许多实用工具方法,用于从基本类型转换到相应的包装器类型和返回,以及从字符串转换到包装器类型和返回。

我在我的博客上写了一篇关于包装器类的详细文章,深入解释了包装器类型的概念——http://www.javabrahman.com/corejava/java-wrapper-classes-tutorial-with-examples/ (披露-这个博客是我所有的)

Java编程为每个基元数据类型提供包装类,用于将基元数据类型转换为包装类的对应对象。

包装类是一个“包装”其他东西的类,就像它的名字一样。

它更正式的定义是实现适配器模式的类。这允许您将一组api修改为更可用、更可读的形式。例如,在c#中,如果你想使用本机Windows API,它有助于将它包装成一个符合. net设计准则的类。