JDK dynamic proxies provide a mechanism to create proxy instances that implement specified interfaces at runtime. Here's a basic implementation:
import java.lang.reflect.*;
interface GreetingService {
void greet();
}
class GreetingServiceImpl implements GreetingService {
public void greet() {
System.out.println("Hello from service");
}
}
class ServiceProxyHandler implements InvocationHandler {
private Object target;
public Object bind(Object target) {
this.target = target;
return Proxy.newProxyInstance(
target.getClass().getClassLoader(),
target.getClass().getInterfaces(),
this
);
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("Before method execution");
Object result = method.invoke(target, args);
System.out.println("After method execution");
return result;
}
}
public class ProxyDemo {
public static void main(String[] args) {
GreetingService proxy = (GreetingService) new ServiceProxyHandler()
.bind(new GreetingServiceImpl());
proxy.greet();
}
}
Output:
Before method execution
Hello from service
After method execution
Multiple Interface Implementation
When a target class implements multiple interfaces, the proxy can handle all of them:
interface Logger {
void logMessage(String msg);
}
class MultiServiceImpl implements GreetingService, Logger {
public void greet() {
System.out.println("Greeting from service");
}
public void logMessage(String msg) {
System.out.println("Logging: " + msg);
}
}
public class MultiInterfaceDemo {
public static void main(String[] args) {
Object proxy = new ServiceProxyHandler()
.bind(new MultiServiceImpl());
((GreetingService)proxy).greet();
((Logger)proxy).logMessage("Test message");
}
}
Output:
Before method execution
Greeting from service
After method execution
Before method execution
Logging: Test message
After method execution
Key points about JDK dynamic proxies:
- The proxy implements all interfaces of the target object
- All method calls are routed through the InvocationHandler
- The proxy also handles Object class methods (equals, hashCode, toString)
- Proxy geneartion ivnolves creating a new class at runtime