Forum Stats

  • 3,852,826 Users
  • 2,264,140 Discussions
  • 7,905,155 Comments

Discussions

After compiling classes with generics, can types still be params?

843793
843793 Member Posts: 41,732 Green Ribbon
edited Jul 31, 2002 9:38AM in Generics

Hello,

As I understand it, generics types are a feature of the compiler, not the compiled class. So if I compile some classes (containing parameterized types/generics), the compiler helps check type safety. But once they're compiled, if generics really are just "a compiler features", in any other Java code that I write that refers to the compiled classes, it seems perfectly possible that I could refer to methods in the compiled class using inappropriate casts/types, because the generic information is present in the source code, and no longer present in the compiled class.

This seems to be a big limitation, as it would mean I'd lose the benefits of generics when working with the core API or compiled classes (especially likely with JAR files...). I must be missing something here, anyone able to help me understand how parameterized types can be used when referring to compiled classes (for which I don't have access to the source code) from my own Java code?

Thanks,
Chris B.

Comments

  • 843793
    843793 Member Posts: 41,732 Green Ribbon
    I can't remember exactly how it works, but I'm pretty sure you won't be allowed to compile code that breaks genericity.

    Remember, a generic class provides genericity, but you provide the parameter. The only situation that breaks this is if member variables are public - which they shouldn't be.
  • 843793
    843793 Member Posts: 41,732 Green Ribbon
    Hi,
    According to the GJ specification, the compiler does store extra parameter information in the class files. There is a process called 'retrofitting' which allows to add this extra information to existing classes.
    The Java 2 Collection classes which come with the generics compiler were retrofitted in this way. If, however, you use the 'raw types' it is possible to compile code which violates type constraints, and which will fail only at runtime (the compiler will give an unchecked warning, though).
  • 843793
    843793 Member Posts: 41,732 Green Ribbon
    No its not a limitation but the nature of late binding. Sure you can use a precompiled class like it were a library and access the methods directly since you will know what the signatures are. You are within your rights to create as many illegal casts as you want. The point is Generics will not itself create any bad casts. Nobody can stop a mad programmer...
This discussion has been closed.