Sobes.tech
Junior — Middle

Does the proxy object create a new instance of the same class as the target object?

sobes.tech AI

Answer from AI

A proxy object in Java typically does not create a new instance of the same class as the target object. Instead, the proxy acts as a wrapper or intermediary that intercepts method calls and can add additional logic (such as logging, caching, transactions).

The proxy implements the same interface or inherits from the class but does not create a new target class object on each call. Instead, it holds a reference to an existing target object and delegates calls to it.

Example using dynamic proxy:

import java.lang.reflect.*;

interface Service {
    void perform();
}

class RealService implements Service {
    public void perform() {
        System.out.println("Performing real work");
    }
}

class ProxyHandler implements InvocationHandler {
    private final Object target;
    public ProxyHandler(Object target) {
        this.target = target;
    }
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("Before method call");
        Object result = method.invoke(target, args);
        System.out.println("After method call");
        return result;
    }
}

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

        proxy.perform();
    }
}

Here, the proxy does not create a new RealService but uses the existing real object.

Does the proxy object create a new instance of the… - sobes.tech