Java Reference
In-Depth Information
the constructor called. Given the dynamic nature of the dynamic proxy, using a regular constructor wouldn't work,
because you need to know the name of the class/ constructor before you can invoke it. When using a constructor
is out of the question, the next best thing is a static method to create an instance. The class
Proxy
has two factory
methods; one (
getProxyClass
) gets the
Class
object that describes the dynamic proxy with the specified
interfaces. The other factory method (
newProxyInstance
) is more of a convenience method. It uses the
getProxyClass
method to get the class, then uses that
Class
to get the constructor and invoke the constructor.
The
Array
class, which is the wrapper class for arrays implements the Factory Method for a different reason.
Creating an array requires knowing the exact type of the elements, and the resulting object is an array of elements
of that particular type, which cannot be changed later. This is like the normal array where you declare the type
when the array is created and cannot be changed. The object created by the factory method is not an instance of
Array
, which eliminates the possibility of using a constructor, because the constructor of
Array
returns an
Array
instance. So instead of a constructor, a Factory Method is used.
Facade
(see page 175): In this API the class
Class
acts as a front to the whole reflection of a real class. The
most-used options are available through the
Class
. The other reflection classes are still available for more
specialized modification, invocation, or reflection.
Proxy
(see page 197): The classes
Field
,
Method
and
Constructor
encapsulate the whole concept of a specific
field, method, or constructor respectively. You can request all information through the reflection classes. For
example, using a
Method
object, which is tied to a specific method in a class, you can request the declared
modifiers, a list of parameter types required to invoke the method, and the return type. You can even use the
Method
object to invoke the method.
The
Method
class acts as a proxy to the specific method. Instead of being a proxy to another object, here the
Field
,
Method
,
Constructor
, and
Modifier
are proxies to parts of an object.
Another implementation of the Proxy pattern is the
Proxy
class. The factory method in the Proxy class creates the
required class for the needed functionality. The resulting subclass of Proxy implements all specified interfaces
and methods. The implementation of the methods are such that all calls are forwarded to the single handler
method inside of the
InvocationHandler
.
To the outside world, an instance of the dynamic proxy behaves as expected. All of its interfaces and all defined
methods can be invoked on the proxy instance. The real implementation of the methods is in the
InvocationHandler.