Looking through some code I came across the following code
trTuDocPackTypdBd.update(TrTuDocPackTypeDto.class.cast(packDto));
and I’d like to know if casting this way has any advantages over
trTuDocPackTypdBd.update((TrTuDocPackTypeDto)packDto);
I’ve asked the developer responsible and he said he used it because it was new (which doesn’t seem like a particularly good reason to me), but I’m intrigued when I would want to use the method.
These statements are not identical. The cast method is a normal method invocation (
invokevirtualJVM instruction) while the other is a language construct (checkcastinstruction). In the case you show above, you should use the second form:(TrTuDocPackTypeDto) packDtoThe
castmethod is used in reflective programming with generics, when you have a Class instance for some variable type. You could use it like this:This gives you a safe way to avoid the incorrect alternative of simply casting a raw type to a generic type:
The compiler will warn you,
Unchecked cast from List to List<Widget>, meaning that in the ellipsis, someone could have added aGadgetto the raw list, which will eventually cause aClassCastExceptionwhen the caller iterates over the returned list of (supposed)Widgetinstances.