Last active
March 30, 2020 05:48
-
-
Save rcook/492a773c698d7a47da090087e328f6ef to your computer and use it in GitHub Desktop.
Unchecked casts in Java
This file contains hidden or 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
| The MIT License (MIT) | |
| Copyright (c) 2019 Richard Cook | |
| Permission is hereby granted, free of charge, to any person obtaining a copy of | |
| this software and associated documentation files (the "Software"), to deal in | |
| the Software without restriction, including without limitation the rights to | |
| use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of | |
| the Software, and to permit persons to whom the Software is furnished to do so, | |
| subject to the following conditions: | |
| The above copyright notice and this permission notice shall be included in all | |
| copies or substantial portions of the Software. | |
| THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | |
| IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS | |
| FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR | |
| COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER | |
| IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN | |
| CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. |
This file contains hidden or 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
| package org.rcook; | |
| import java.util.Optional; | |
| class Foo { | |
| @Override | |
| public String toString() { | |
| return "this is a foo"; | |
| } | |
| } | |
| public class Main { | |
| private static Optional<String> returnsOptionalString() { | |
| return Optional.of("hello"); | |
| } | |
| private static Object returnsOptionalStringWithTypesErased() { | |
| return returnsOptionalString(); | |
| } | |
| private static void testNoCastNoFailure() { | |
| // No failure since the object is not coerced to any particular type | |
| System.out.println(returnsOptionalStringWithTypesErased()); | |
| } | |
| private static void testUncheckedCastNoFailure() { | |
| // Without the @SuppressWarnings annotation, the compiler will warn that it | |
| // cannot prove that the object is really Optional<String>. Given that | |
| // Optional<String> is an instantiation of a generic type, it's even worse | |
| // than this: Optional<String> cannot even be distinguished from | |
| // Optional<T> (T != String) at runtime until the point at which the contents | |
| // of the Optional are coerced to a specific type by a cast etc. | |
| // Must suppress warning if compiled with -Xlint:unchecked -Werror | |
| @SuppressWarnings("unchecked") | |
| Optional<String> optStr = (Optional<String>) returnsOptionalStringWithTypesErased(); | |
| // No failure since the object is not coerced to any particular type | |
| System.out.println(optStr); | |
| } | |
| private static void testUncheckedCastToIncorrectTypeFailsOnDereference() { | |
| // Without the @SuppressWarnings annotation, the compiler will warn that it | |
| // cannot prove that the object is really Optional<Foo>. Given that | |
| // Optional<Foo> is an instantiation of a generic type, it's even worse | |
| // than this: Optional<Foo> cannot even be distinguished from | |
| // Optional<T> (T != Foo) at runtime until the point at which the contents | |
| // of the Optional are coerced to a specific type by a cast etc. | |
| // Must suppress warning if compiled with -Xlint:unchecked -Werror | |
| @SuppressWarnings("unchecked") | |
| Optional<Foo> optFoo = (Optional<Foo>) returnsOptionalStringWithTypesErased(); | |
| // Doesn't fail here since this doesn't coerce the object to specific type | |
| System.out.println(optFoo); | |
| // Doesn't fail here since this doesn't coerce the object in the Optional to a specific type | |
| System.out.println(optFoo.get()); | |
| // This is where we first "dereference" the contents of the Optional: | |
| // ClassCastException is thrown here even though (syntactically, at least) | |
| // there is no cast here | |
| Foo foo = optFoo.get(); | |
| System.out.println(foo); | |
| } | |
| private static void testExplicitCastToIncorrectTypeFailsEarly() { | |
| // Here we're honest: we cannot (easily) formally prove that it's an Optional<Foo> | |
| // (which it isn't anyway!) so, instead, we admit that we don't know its contained type: | |
| // ClassCastException is thrown here and not deferred until the types are coerced later | |
| Optional<Foo> optFoo = ((Optional<?>) returnsOptionalStringWithTypesErased()).map(x -> (Foo) x); | |
| // Never reached | |
| System.out.println(optFoo); | |
| // Never reached | |
| System.out.println(optFoo.get()); | |
| // Never reached: no strange ClassCastException to leave one scratching one's head | |
| Foo foo = optFoo.get(); | |
| System.out.println(foo); | |
| } | |
| public static void main(String[] args) { | |
| test("testNoCastNoFailure", Main::testNoCastNoFailure); | |
| test("testUncheckedCastNoFailure", Main::testUncheckedCastNoFailure); | |
| test("testUncheckedCastToIncorrectTypeFailsOnDereference", Main::testUncheckedCastToIncorrectTypeFailsOnDereference); | |
| test("testExplicitCastToIncorrectTypeFailsEarly", Main::testExplicitCastToIncorrectTypeFailsEarly); | |
| } | |
| private static void test(String name, Runnable runnable) { | |
| try { | |
| System.out.format("BEGIN: %s%n", name); | |
| runnable.run(); | |
| System.out.format("END: %s%n", name); | |
| } catch (final Exception e) { | |
| System.out.format("END(Exception): %s (at line %d: %s)%n", name, e.getStackTrace()[0].getLineNumber(), e); | |
| } | |
| System.out.println(); | |
| } | |
| } |
This file contains hidden or 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
| BEGIN: testNoCastNoFailure | |
| Optional[hello] | |
| END: testNoCastNoFailure | |
| BEGIN: testUncheckedCastNoFailure | |
| Optional[hello] | |
| END: testUncheckedCastNoFailure | |
| BEGIN: testUncheckedCastToIncorrectTypeFailsOnDereference | |
| Optional[hello] | |
| hello | |
| END(Exception): testUncheckedCastToIncorrectTypeFailsOnDereference (at line 61: java.lang.ClassCastException: java.lang.String cannot be cast to org.rcook.Foo) | |
| BEGIN: testExplicitCastToIncorrectTypeFailsEarly | |
| END(Exception): testExplicitCastToIncorrectTypeFailsEarly (at line 69: java.lang.ClassCastException: java.lang.String cannot be cast to org.rcook.Foo) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment