Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save torgeir/f3b65dc7a14ed92d97a73d7576106b36 to your computer and use it in GitHub Desktop.
Save torgeir/f3b65dc7a14ed92d97a73d7576106b36 to your computer and use it in GitHub Desktop.
Java example showing how a proxied methods return type may cause runtime class cast errors
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
class DynamicInvocationHandler implements InvocationHandler {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
return 42;
}
}
interface Thing {
public String getIt();
}
class ExampleProxyMethodReturnTypeMismatch {
public static void main(String[] args) {
Thing t =
(Thing) Proxy.newProxyInstance(
ExampleProxyMethodReturnTypeMismatch.class.getClassLoader(),
new Class[]{Thing.class},
new DynamicInvocationHandler());
System.out.println(t.getIt());
}
}
/Library/Java/JavaVirtualMachines/temurin-17.jdk/Contents/Home/bin/java ....
Exception in thread "main" java.lang.ClassCastException: class java.lang.Integer cannot be cast to class java.lang.String (java.lang.Integer and java.lang.String are in module java.base of loader 'bootstrap')
at $Proxy0.getIt(Unknown Source)
at ExampleProxyMethodReturnTypeMismatch.main(scratch_9.java:28)
Process finished with exit code 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment