A proxy is essentially an intermediary between the client and the object, so that it implements non-finite methods of the object. Proxying an interface is relatively simple because the interface is just a list of methods that you need to implement, which makes it easy to intercept method calls.
The Java Proxy class is a class that implements a list of interfaces that are specified at runtime. Then the proxy has an InvocationHandler associated with it , which delegates method calls made in the proxy to the proxied object. It acts as a level of indirection, so methods are not called on the object itself, but rather on its proxy. InvocationHandlerhas only one method that needs to be implemented:
public Object invoke(Object proxy, Method method, Object[] args)
, , , - .
, , . Java Proxy , . -, , cglib. cglib -, - (.. ), , Java Proxy .
. - . Lazy loading , . , , , " ", , , . . . . , , , . -, , .
:
public abstract class LazilyLoadedObject implements InvocationHandler {
private Object target;
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (target == null) {
target = loadObject();
}
return method.invoke(target, args);
}
protected abstract Object loadObject();
}
InvocationHandler , , -, InvocationHandler. , . , loadObject(), - , .
, . .