0-TestYourJava - Cast without exception

Moderatoren: pmueller, SE - Design and Construction

GS-812
Windoof-User
Windoof-User
Beiträge: 30
Registriert: 25. Apr 2015 12:47

0-TestYourJava - Cast without exception

Beitrag von GS-812 »

Hello,

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:
TestYourJava.java
(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:
TestYourJavaV1.java
(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.

eichberg
Moderator
Moderator
Beiträge: 448
Registriert: 25. Sep 2007 12:12
Kontaktdaten:

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;
        System.out.println("successful");
        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.

Antworten

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