0-TestYourJava - Cast without exception

Moderatoren: pmueller, SE - Design and Construction

Beiträge: 30
Registriert: 25. Apr 2015 12:47

0-TestYourJava - Cast without exception

Beitrag 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) 23-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) 14-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.

Beiträge: 448
Registriert: 25. Sep 2007 12:12

Re: 0-TestYourJava - Cast without exception

Beitrag 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.


Zurück zu „Software Engineering - Design and Construction“