Dynamic Proxy and UndeclaredThrowableException
date
Mar 24, 2022
slug
dynamic-proxy-and-UndeclaredThrowableException
status
Published
tags
Java
summary
type
Post
Background
In an exercise about Dynamic Proxy, I implemented a dynamic proxy that implements the
Client
interface by looking in the map
for the name properties.The underlying delegate object is a
map
, which is different from the interface that the proxy object implements (So we could say that this dynamic proxy acts as an adapter).Here is a code snippet from the custom
InvocationHandler
:Code Explaining
All Java objects inherit methods from
Object
class like toString
, equals
and hashCode
.In this exercise, we are not concerned about these methods. We want to intercept only
get
methods defined in the Client
interface.So we check whether a method is declared in the
Object
class, and just invoke the method with the original arguments. This is like ignoring the proxy.But we should also take care if these methods (
toString
, equals
, hashCode
) throw an exception.Notice that
method.invoke()
would rethrow that exception wrapped in an InvocationTargetException
.We don’t want to change the behavior of these methods, so we should unwrap the exception and rethrow it exactly as the method call will do if no proxy exists:
But there is a special case where a UndeclaredThrowableException may be thrown and we should treat it also.