11

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?

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
fortran
  • 74,053
  • 25
  • 135
  • 175

5 Answers5

14

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
  • 2,273
  • 2
  • 18
  • 26
  • 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 Aug 17 '10 at 13:24
  • posting the answer 1 minute before also makes a difference ;-) – fortran Aug 17 '10 at 13:41
  • 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 Aug 17 '10 at 13:43
  • @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. – Pops Sep 01 '10 at 17:28
13

If you're using Android Studio it's an easy fix: Analyze > Code Cleanup

Bobby
  • 6,115
  • 4
  • 35
  • 36
4

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
  • 1,421,763
  • 867
  • 9,128
  • 9,194
2

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
  • 7,908
  • 2
  • 36
  • 33
  • 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 Aug 17 '10 at 13:30
1

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

musiKk
  • 14,751
  • 4
  • 55
  • 82