Java Reference
In-Depth Information
Dynamic Proxies
One last piece of the Java Reflection story is the creation of dynamic proxies. These
are classes (which extend
java.lang.reflect.Proxy
) that implement a number of
interfaces. The implementing class is constructed dynamically at runtime, and for‐
wards all calls to an invocation handler object:
g
R
e
l
e
c
t
i
o
n
InvocationHandler
h
=
new
InvocationHandler
()
{
@Override
public
Object
invoke
(
Object
proxy
,
Method
method
,
Object
[]
args
)
throws
Throwable
{
String
name
=
method
.
getName
();
System
.
out
.
println
(
"Called as: "
+
name
);
switch
(
name
)
{
case
"isOpen"
:
return
false
;
case
"close"
:
return
null
;
}
d
return
null
;
}
};
Channel
c
=
(
Channel
)
Proxy
.
newProxyInstance
(
Channel
.
class
.
getClassLoader
(),
new
Class
[]
{
Channel
.
class
},
h
);
c
.
isOpen
();
c
.
close
();
Proxies can be used as stand-in objects for testing (especially in test mocking
approaches).
Another use case is to provide partial implementations of interfaces, or to decorate
or otherwise control some aspect of delegation:
public
class
RememberingList
implements
InvocationHandler
{
private
final
List
<
String
>
proxied
=
new
ArrayList
<>();
@Override
public
Object
invoke
(
Object
proxy
,
Method
method
,
Object
[]
args
)
throws
Throwable
{
String
name
=
method
.
getName
();
switch
(
name
)
{
case
"clear"
:
return
null
;
case
"remove"
:
case
"removeAll"
:
return
false
;
}
return
method
.
invoke
(
proxied
,
args
);