Sobes.tech
Junior — Middle

How can a proxy object be implemented to control access or add additional logic?

sobes.tech AI

Answer from AI

A proxy object in Java can be implemented using the "Proxy" pattern or dynamic proxies to control access or add additional logic when calling methods.

Example using a dynamic proxy:

import java.lang.reflect.*;

interface Service {
    void perform();
}

class RealService implements Service {
    public void perform() {
        System.out.println("Executing core logic");
    }
}

class ProxyHandler implements InvocationHandler {
    private final Object realObject;

    public ProxyHandler(Object realObject) {
        this.realObject = realObject;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("Access check before method call");
        Object result = method.invoke(realObject, args);
        System.out.println("Additional logic after method call");
        return result;
    }
}

public class ProxyExample {
    public static void main(String[] args) {
        Service realService = new RealService();
        Service proxyInstance = (Service) Proxy.newProxyInstance(
            Service.class.getClassLoader(),
            new Class[]{Service.class},
            new ProxyHandler(realService));

        proxyInstance.perform();
    }
}

This proxy allows intercepting method calls, adding checks or logic before and after calling the real object.