This interface defines an invocation handler. Suppose you are using
reflection, and found a method that requires that its parameter
be an object of a given interface. You want to call this method,
but have no idea what classes implement that interface. So, you can
create a Proxy instance, a convenient way to dynamically
generate a class that meets all the necessary properties of that
interface. But in order for the proxy instance to do any good, it
needs to know what to do when interface methods are invoked! So,
this interface is basically a cool wrapper that provides runtime
code generation needed by proxy instances.
While this interface was designed for use by Proxy, it will also
work on any object in general.
Hints for implementing this class:
- Don't forget that Object.equals, Object.hashCode, and
Object.toString will call this handler. In particular,
a naive call to proxy.equals, proxy.hashCode, or proxy.toString
will put you in an infinite loop. And remember that string
concatenation also invokes toString.
- Obey the contract of the Method object you are handling, or
the proxy instance will be forced to throw a
NullPointerException, ClassCastException,
or UndeclaredThrowableException.
- Be prepared to wrap/unwrap primitives as necessary.
- The Method object may be owned by a different interface than
what was actually used as the qualifying type of the method
invocation in the Java source code. This means that it might
not always be safe to throw an exception listed as belonging
to the method's throws clause.
For a fun time, create an InvocationHandler that handles the
methods of a proxy instance of the InvocationHandler interface!
When a method is invoked on a proxy instance, it is wrapped and
this method is called instead, so that you may decide at runtime
how the original method should behave.
NullPointerException. In all remaining cases, if
the returned object is not assignment compatible to the
declared type of the original method, the proxy instance
will generate a ClassCastException.
While this interface was designed for use by Proxy, it will also work on any object in general.
Hints for implementing this class:
For a fun time, create an InvocationHandler that handles the methods of a proxy instance of the InvocationHandler interface!