how to create wrapper class for any user defined class

kawade picture kawade · Apr 20, 2011 · Viewed 27.8k times · Source

someone told me that we can create wrapper class for any user defined class instead of only for primitives, if yes! then how can we create it, i have no idea about that from where to start, would you please provide any demo code for this purpose. awaiting for your responses....

Answer

BoffinBrain picture BoffinBrain · Apr 20, 2011

The term 'wrapping' sometimes means the same thing as encapsulation, where an object or type is used internally by a class as part of its implementation details, and doesn't expose it to outside code. However, wrapping often refers specifically to the act of encapsulating a class in another class which implements the same interface as the wrapped class but changes its behaviour slightly or adds new features (Decorator Pattern), or the outer class implements a different interface, essentially converting the wrapped class to make it compatible with another program (Adapter Pattern). Both of these types of wrapping are nearly always done manually, and must be done at compile-time (by writing code).

You can also generate dynamic proxies for virtually any object at runtime using java.lang.reflect.Proxy.newProxyInstance(...). You can read the official guide on Dynamic Proxy Classes to learn how to use it. However, you haven't given any use cases yet, so this might not be what you're looking for. Proxies are usually reserved for protecting objects or delegating to a remote server via RPC, and can be very complex.