Proxy Interfaces In Java
#java #programmingJava provides a static method Proxy.newProxyInstance
as part of it’s Reflection API. This static method returns a proxy class for a given set of interfaces.
It requires only 3 things:
- A class loader
- A list of interfaces that this proxy should implement
- An
InvacationHandler
. This is like a callback which is invoked when methods on this proxy are called.
Proxy Class Properties
- The proxy classes are
public
,final
andnon-abstract
- This proxy classes extend
java.lang.reflect.Proxy
- Implements all interfaces provided (in the order) at the time of creation
proxy instanceof Foo
returnstrue
and(Foo) proxy
succeeds without anyClassCastExceptions
public interface Account {
BigInteger computeBalance(BigInteger considerDeductions);
}
InvocationHandler handler = new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println(method); // the method that is being called
System.out.println(args); // parameters passed to that method
return BigInteger.ONE;
}
};
Account accountProxy = (Account) Proxy.newProxyInstance(
Account.class.getClassLoader(),
new Class[]{
Account.class
},
handler
);
System.out.println(accountProxy.computeBalance(BigInteger.ZERO));
Use Cases
- Mockito and similar libraries
- When you want to make batched calls