什么是包装器类? 这样的类有什么用处呢?
当前回答
包装器类提供了一种将基本类型用作对象的方法。对于每个原语,我们都有一个包装器类,比如,
int Integer
byte Byte
Integer和Byte是原语int和Byte的包装类。当您需要将原语作为对象使用时,有时会有限制,因此包装类提供了一种称为装箱/拆箱的机制。
下面的例子可以很好地理解这个概念
double d = 135.0 d;
Double doubleWrapper = new Double(d);
int integerValue = doubleWrapper.intValue();
byte byteValue = doubleWrapper.byteValue();
string stringValue = doubleWrapper.stringValue();
这就是方法,我们可以使用包装器类类型转换成其他基本类型。当您需要将原语类型转换为对象并使用它们来获取其他原语时,就会使用这种类型的转换。但是对于这种方法,您需要编写一个大代码。但是,使用简单的强制转换技术也可以实现同样的效果,代码片段如下所示
double d = 135.0;
int integerValue = (int) d ;
虽然double值显式转换为整数值,也称为向下转换。
其他回答
Java编程为每个基元数据类型提供包装类,用于将基元数据类型转换为包装类的对应对象。
有几种设计模式可以称为包装器类。
请参阅我对“代理、装饰器、适配器和桥接模式有何不同?”
包装器类是围绕基本数据类型的包装器。它表示基元数据类型在其对应的类实例中,例如布尔数据类型可以表示为布尔类实例。Java中所有的基本包装类都是不可变的,即一旦给包装类实例赋值,就不能再修改。
值得注意的是,在某些环境中,包装器类所做的大部分工作都被方面所取代。
编辑:
一般来说,包装器将对包装所做的事情进行扩展,而不关心包装的实现,否则,包装与扩展被包装的类没有任何意义。一个典型的例子是围绕一些其他服务接口添加计时信息或日志功能,而不是将其添加到该接口的每个实现中。
This then ends up being a typical example for Aspect programming. Rather than going through an interface function by function and adding boilerplate logging, in aspect programming you define a pointcut, which is a kind of regular expression for methods, and then declare methods that you want to have executed before, after or around all methods matching the pointcut. Its probably fair to say that aspect programming is a kind of use of the Decorator pattern, which wrapper classes can also be used for, but that both technologies have other uses.
包装器类是一个包装另一个类并提供客户端和被包装的原始类之间的抽象的类。