Re: A Generic Generics Problem
- From: Jon Skeet [C# MVP] <skeet@xxxxxxxxx>
- Date: Thu, 17 May 2007 21:39:15 +0100
rkausch@xxxxxxxxx <rkausch@xxxxxxxxx> wrote:
Thanks for the quick reply. If I recall correctly, since Java uses
generics in such a way as to not break the legacy JVMs, it basically
replaces all instances of "T" with the actual type at compile time,
and effectively retains the type safety at run time (you'll get a
class cast exception if you try to put something other than type T
into the object, for example).
No - it replaces all instances of "T" with java.lang.Object in the
generic type, and puts runtime casts in the calling code. Here's an
example:
import java.io.*;
import java.util.*;
public class Test
{
public static void main (String[] args)
{
ArrayList<String> strings = new ArrayList<String>();
strings.add("Hello");
Object foo = strings;
ArrayList<File> files = (ArrayList<File>) foo;
System.out.println ("Got past the cast");
File x = files.get(0);
}
}
You'll get a warning at compile time, but it *will* compile. It will
then fail later than you really want.
I realize that C# generics are not
implemented this way, which is the crux of the situation. Basically,
I suppose I'm asking for the impossible: the type safety of generics
to be preserved, regardless of how the pointer to the object is being
used (this probably would work in C++ using templates, since n classes
are generated, one for each variation of type T used).
But my point is that the object couldn't be particularly usefully used
any more, because you no longer (at compile-time) have any information
about the original type arguments.
Now, you could make your type implement a non-generic interface if you
don't need to expose the type parameters in the API, but if you want to
keep a strongly typed API, you need the type parameters.
Does the
underlying object preserve the type information after it's created, or
is that always handled by the syntax of the declaration (e.g.
List<String> always knows that it can only take a String because the
syntax says <String>, not because the List object preserved String
internally)?
No, a List<string> preserves its type. If you try the equivalent to the
above code with C#, you'll get a casting exception when you cast the
list, not when you try to access elements within it.
--
Jon Skeet - <skeet@xxxxxxxxx>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
.
- Follow-Ups:
- Re: A Generic Generics Problem
- From: rkausch@xxxxxxxxx
- Re: A Generic Generics Problem
- References:
- Re: A Generic Generics Problem
- From: Jon Skeet [C# MVP]
- Re: A Generic Generics Problem
- From: rkausch@xxxxxxxxx
- Re: A Generic Generics Problem
- Prev by Date: Re: Access a Control by its name as a string
- Next by Date: XMLSerializer, socket
- Previous by thread: Re: A Generic Generics Problem
- Next by thread: Re: A Generic Generics Problem
- Index(es):
Relevant Pages
|