Re: Erased data type
Brian Goetz <[email protected]>
| Newsgroups | gmane.comp.windows.devel.java.advanced |
|---|---|
| Message-ID | <[email protected]> |
This advice is correct, but I would warn you to be careful. In a
significant percentage of cases where the compiler warns of an unchecked
cast, there really is a type-safety issue there -- and simply supressing
the compiler warning just sweeps it under the rug. Some of the type
safety issues are surprisingly subtle. And, if you must suppress
warnings, factor out the "unsafe" code into a small method, to reduce
the scope of the @SuppressWarnings annotation, to avoid hiding other errors.
James Childers wrote:
> On Aug 30, 2007, at 10:10 AM, Mann, Ivan H wrote:
>
>> I have an app with a gui that can develop a lot of data. There is a
>> save button, which writes the data out using serialization.
>>
>> Then, there is a load button, which reads the data back in, using this
>> line:
>>
>> destinations = (ArrayList<ScheduleDestination>)
>> is.readObject()
>> ;
>>
>> Where destinations is defined elsewhere as
>>
>> ArrayList<ScheduleDestination> destinations ;
>>
>> On the line that reads the object back in, there is a compiler flag:
>>
>> Type Safety: The cast from Object to
>> ArrayList<ScheduleDestination> is actually checking against the erased
>> type ArrayList.
>>
>> What does this flag mean? I have googled fairly creatively and can't
>> find anything which tells me what it means or how to make it go away.
>
> @suppressWarnings("unchecked")
>
> will make the warning go away.
>
> The reason you are seeing it is that generic declarations aren't
> saved when the object is serialized; generics are purely a compile-
> time mechanism. Once the code is compiled into bytecode all generic
> references are for all practical purposes erased.
>
> Yes, this is annoying. It also means that utilizing legacy objects
> that do not themselves understand generics will cause your
> declarations to be lost. A common example is in a servlet container
> that uses Java5 but an older version of J2EE. In this case the
> following would also give a warning:
>
> List<String> myList = new ArrayList<String>();
> request.setAttribute("myList", myList);
> List<String> myNewList = (ArrayList<String>) request.getAttribute
> ("myList"); // Erased type warning here
>
> -= J
>
> ===================================
> This list is hosted by DevelopMentor® http://www.develop.com
>
> View archives and manage your subscription(s) at http://discuss.develop.com
===================================
This list is hosted by DevelopMentor® http://www.develop.com
View archives and manage your subscription(s) at http://discuss.develop.com