views:

307

answers:

4

I like generics a lot and use them whereever I can. Every now and then I need to use one of my classes in another project which has to run on an old JVM (before 5.0), needs to run on JavaME (where generics are not allowed neither) or in Microsoft J# (which has VERY poor Support for generics).

At the moment, I remove all generics manually, which means inserting many casts as well.

Since generics are said to be compile-time-only, and every piece of generic code could possibly converted to non-generic code automatically, I wonder if there is any tool which can do this for me.

If there is no such tool, how else could I solve the problem? Should I completely stop using generics?

There already are answers related to bytecode compability. What if I need source code compability for some reason?

A: 

Its bytecode compatible, it should work out of the box with an old interpreter.

flolo
1.5 compiled classes have a different version number in the class. The class won't load in previous versions of Java.
Ken Gentle
Of course you have to compile with -target / -source to embedd this information.
flolo
@flolo: if you specify source 1.5 then source 1.4 is not allowed. Have you actually tried this?
Hemal Pandya
Hemal, you mean -source 1.5 -target 1.4 is disallowed.
Tom Hawtin - tackline
+2  A: 

In Netbeans (I'm not sure about what IDE you are using) you can set the source-code compatibility to a set java version - just set it to one that supports generics. As already posted, generics are bytecode compatable with old JVM / JRE versions and so it should hopefully work out of the box.

Richie_W
+2  A: 

To the best of my knowledge Java 5 is not byte-code compatible with Java 1.4. That is, You cannot use Java 5 compiled classes with an earlier VM.

You can check retroweaver. This was mentioned a lot when generics were introduced. I personally have no experience with it.

Did you ask Google? My search turned up http://www.publicobject.com/glazedlists/documentation/Generics_and_Java_1.4_with_one_codebase.pdf, which seems a very interesting approach.

Hemal Pandya
That's exactly what I was looking for, thanks! The pdf you linked just described the tool. You can actually download it at http://sites.google.com/site/glazedlists/Home/declawer
Brian Schimmel
+5  A: 

You need to use something like Retroweaver in order to achieve this sort of thing. The other answers on this question are slightly misleading. Generics are sort-of bytecode compatible with previous versions, but not entirely (see java.lang.reflect.Type if you don't believe me). Also, there is an issue of the bytecode version attribute, which will prevent a class compiled against 1.5 from running on a previous version. Retroweaver works around both problems while also enabling other Java 5 features like annotations and enums.

Daniel Spiewak