Created
June 6, 2023 08:35
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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()); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/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