views:

126

answers:

4

Is there a tool that would allow me to check use of generic collections in code that must be compilable with Java 1.4? I would imagine example code as:

Map/*<String, Integer>*/ map = new HashMap();
map.put("abc", new Integer(3));  // ok
map.put("def", "ghi");  // warning

EDIT: Unfortunately the build process is "set in stone" to use Java 1.4, so the code I commit cannot contain any 1.5 features, or depend on any translation tools. The easiest solution so far seems to be maintaining local version of code for 1.5, and converting it to 1.4 before commit.

+1  A: 

I'd recommend coding for 1.5 and using a tool like declawer (google for it, there are various updates to the original version floating around) to strip off the generics when you need to build 1.4 compatible code.

Works for us (although we added some features to the original declawer so that it could parse our source files).

mitchnull
Declawer looks promising, thanks!
A: 

Use -source 1.4 as a flag to the javac command. Here are the details.

Hank Gay
That will not perform the checks I would like, will it?
Perhaps I misunderstood your question. I interpreted it as "find places where I'm using generic collections so I can fix them for compiling with 1.4".
Hank Gay
A: 

Is the requirement really to compileable against 1.4, or only that it can run on 1.4? In the latter case, you can use Retroweaver. Or, if you only want to use generics, just compile with the undocumented -target jsr14 option.

But I'm pretty sure there isn't anything like you describe - what would be the point?

Michael Borgwardt
The final code must compile against 1.4. The point is to get some extra error checking without too much hassle.
A: 

I'm not sure if I get this right: You want to write that comment "<String, Integer>" in your code and run some Static code analysis tool to check if it would compile?

I don't think there is such a thing right now but you should check out findbugs. Findbugs will help you with generics and stuff like this:

List<String> list = new ArrayList<String>();
list.add("foo");
list.contains(new Integer(5));

This is compilable code, because contains is not generic for compatibility reasons. However, findbugs gives you a nice warning for that.

Maybe you could write a findbugs detector yourself, that does what you need, but since finbugs works on byte code, you would need to use something different then comments e.g. annotations.

Tim Büthe
Such tool is exactly what I had in mind. If findbugs works only on bytecode, I do not see how I could pass some extra information to my detector, without making the code require Java 1.5.
I think there are backports of annotations for Java 1.4 but never used them myself. Google "java annotations backport"
Tim Büthe