Sobes.tech
Junior — Middle

Is an object proxy passed as an argument when creating its instance?

sobes.tech AI

Answer from AI

A proxy object itself is not passed as an argument when creating its instance. A proxy is an object that controls access to another object (the real subject). Usually, a proxy is created using factory methods or dynamic proxies, and a reference to the real object, which it will wrap, is passed to the proxy's constructor.

That is, when creating a proxy, the proxy object itself is not passed as an argument; instead, the proxy is created around the real object, which is passed to the proxy's constructor.

Example:

public interface Service {
    void execute();
}

public class RealService implements Service {
    public void execute() {
        System.out.println("Executing real service");
    }
}

public class ProxyService implements Service {
    private RealService realService;

    public ProxyService(RealService realService) {
        this.realService = realService; // the real object is passed to the proxy
    }

    public void execute() {
        System.out.println("Proxy: additional logic before call");
        realService.execute();
    }
}

// Usage
RealService real = new RealService();
ProxyService proxy = new ProxyService(real); // proxy is created with the real object
proxy.execute();
Is an object proxy passed as an argument when… - sobes.tech