views:

110

answers:

4

Hi,

I've been generifying some Java code that used lots of casts, and now most of them are redundant and unnecessary.

It could be very tedious to inspect all the usages of the code to remove them, so: are there any tools to help to identify (and remove) superfluous casts?

Thanks!

A: 

In Eclipse, under "warnings and errors" you can set "Unnecessary cast or instanceof operations" to be "Warn" or "Error" rather than "Ignore". That should help you find them very quickly, although it won't clean them up for you.

But you can also set a "Save" action configured with an "Additional action" of "Remove unnecessary casts".

And you can right-click on an area of Package Explorer, select "Clean up..." and configure that with a "Remove unnecessary casts" action.

So basically this should be simple :)

Jon Skeet
+2  A: 

You should probably use a tool to analyze your Java source code for potential problems (such as unnecessary casting).

Perhaps you can try PMD: http://pmd.sourceforge.net

Bernard
Do abstract syntax tree contain these unnecessary casts? I inspected a class file and it seems to me that compiler optimizes them out. But I guess AST contains them yet.
pcjuzer
+1  A: 

If you use Eclipse, this should be fairly easy. Right click the class/package/project and select Source - Clean Up....

musiKk
+12  A: 

This can be automatically done using Eclipse Helios. In your project, go to Properties -> Java code Style -> Clean Up. There, edit a profile, go to the "Unnecessary Code" Tab and check "Remove unnecessary casts". Then right-click your source root and klick Source-> Clean up. Job done.

alt text

Sylar
wonderful! :-D I used to be an Eclipse user, but lately I've been using more NetBeans... Maybe it's about time to come back ^_^
fortran
note to self: screenshot == big rep
musiKk
posting the answer 1 minute before also makes a difference ;-)
fortran
Note: It's also useful to not only configure stuff like that in the cleanup actions but also under "Save Actions" so every time you save a file some of this nice things are automatically applied. (e.g. also making parameters, etc. final if it's possible)
Johannes Wachter
@fortran, sounds like this worked for you; would you consider accepting it? It's not a big deal, but I was going through older questions with no accepted answer and there doesn't seem to be much more to say here.
Lord Torgamus
oh, sorry, I thought I had already done it!
fortran