Seite 1 von 1

0-TestYourJava - Cast without exception

Verfasst: 21. Okt 2017 13:53
von GS-812

I want to point out, that most of the code "TestYourJava" Version 2 may work as expected but also may fail.

The given code will fail:
(661 Bytes) 20-mal heruntergeladen
is Object? false
is null? false
is String? true
is Double? false
Whereas if our write

Code: Alles auswählen

Double o = null;
an exception will be thrown:
(668 Bytes) 11-mal heruntergeladen
is Object? false
Bob: ### java.lang.String cannot be cast to java.lang.Double ###
is null? true
is Double? false
So the function

Code: Alles auswählen

private static <T> T cast(Object i)
may work in some cases.

Re: 0-TestYourJava - Cast without exception

Verfasst: 23. Okt 2017 11:24
von eichberg
Well, if you change the declared type of the variable o, the example is surely no longer the same. But – more important - the method cast is not the one that is throwing the class cast exception in your example. If you change the method as follows:

Code: Alles auswählen

    private static <T> T cast(Object i) {
        System.out.print("cast ");
        T t =  (T) i;
        return t;
you'll see that the method is always successful. The exception is thrown when the return value is assigned to local variable o. Moreover, to get the code compiling you had to comment out the line

Code: Alles auswählen

System.out.println("is String?\t" +(o instanceof String));
, which is another hint that the change had – type wise – a more significant impact.