Junior — Middle
Is it possible to implement a proxy object for a regular class without using Spring framework tools?
sobes.tech AI
Answer from AI
Yes, a proxy object for a regular class can be implemented without Spring, using standard Java tools. For example, you can apply dynamic proxies via java.lang.reflect.Proxy for interfaces or use the CGLIB library for proxying classes without interfaces.
Example of a dynamic proxy for an interface:
import java.lang.reflect.*;
interface Service {
void execute();
}
class ServiceImpl implements Service {
public void execute() {
System.out.println("Executing the execute method");
}
}
class ProxyHandler implements InvocationHandler {
private final Object target;
public ProxyHandler(Object target) {
this.target = target;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("Before calling the method");
Object result = method.invoke(target, args);
System.out.println("After calling the method");
return result;
}
}
public class Main {
public static void main(String[] args) {
Service original = new ServiceImpl();
Service proxy = (Service) Proxy.newProxyInstance(
Service.class.getClassLoader(),
new Class[]{Service.class},
new ProxyHandler(original)
);
proxy.execute();
}
}
If the class does not implement an interface, CGLIB can be used to create proxies based on inheritance.