CKTIS / Java
java.lang.reflect.Proxy — dynamic interface proxies
Proxy.newProxyInstance creates an object implementing specified interfaces at runtime. Calls go to an InvocationHandler, which determines the result instead of using an ordinary method implementation.
Version: Java SE 21; repository runtime, production runtime not attested
Syntax
Object proxy = Proxy.newProxyInstance(loader, interfaces, h);java.lang.reflect.Proxy creates dynamic interface implementations, not subclasses of arbitrary classes. Proxy.newProxyInstance(loader, interfaces, h) takes a class loader, an interface array and an InvocationHandler; it returns an Object that can be cast to a supplied interface. Interfaces must be visible to the loader and must not be hidden or sealed. Non-public interfaces must share a package and module.
The handler receives proxy, a Method object and an argument array; the array may be null for a call without arguments. If the proxy method is declared void, the handler’s return value is discarded. Otherwise, the value must be compatible with the method’s return type, using the corresponding wrapper type for a primitive return type. An undeclared checked exception is wrapped in UndeclaredThrowableException.
Calls to equals, hashCode and toString also reach the handler. Do not invoke the same method on proxy inside it: that re-enters the handler. Methods declared default are intercepted too; their implementation can be called through InvocationHandler.invokeDefault.
The example creates a Greeting without a separate implementation class. Its handler builds the greeting and explicitly handles the three Object methods. This entry targets Java SE 21; production runtime compatibility is not attested.
Examples
import java.lang.reflect.Proxy;
public class Main {
public interface Greeting {
String hello(String name);
}
public static void main(String[] args) {
Greeting greeting = (Greeting) Proxy.newProxyInstance(
Greeting.class.getClassLoader(),
new Class<?>[] { Greeting.class },
(proxy, method, values) -> {
if (method.getDeclaringClass() == Object.class) {
return switch (method.getName()) {
case "equals" -> proxy == values[0];
case "hashCode" -> System.identityHashCode(proxy);
case "toString" -> "GreetingProxy";
default -> throw new UnsupportedOperationException(method.getName());
};
}
return "Hello, " + values[0] + "!";
});
System.out.println(greeting.hello("Ada"));
System.out.println(greeting);
}
}Result
Hello, Ada! GreetingProxy
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.