删除 Java 中的冗余强制转换
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3502690/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Remove redundant casts in Java
提问by fortran
I've been generifyingsome Java code that used lots of casts, and now most of them are redundant and unnecessary.
我一直在生成一些使用大量强制转换的 Java 代码,现在它们中的大多数都是多余的和不必要的。
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?
检查代码的所有用法以删除它们可能非常乏味,因此:是否有任何工具可以帮助识别(和删除)多余的强制转换?
回答by Sylar
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.
这可以使用 Eclipse Helios 自动完成。在您的项目中,转到属性 -> Java 代码样式 -> 清理。在那里,编辑配置文件,转到“不必要的代码”选项卡并选中“删除不必要的强制转换”。然后右键单击您的源根目录并单击 Source-> Clean up。任务完成。


回答by Bobby
If you're using Android Studio it's an easy fix: Analyze > Code Cleanup
如果您使用的是 Android Studio,则可以轻松修复:分析 > 代码清理
回答by Jon Skeet
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.
在 Eclipse 中,在“警告和错误”下,您可以将“不必要的强制转换或操作实例”设置为“警告”或“错误”而不是“忽略”。这应该可以帮助您很快找到它们,尽管它不会为您清理它们。
But you can alsoset a "Save" action configured with an "Additional action" of "Remove unnecessary casts".
但是您也可以设置一个“保存”操作,配置为“删除不必要的强制转换”的“附加操作”。
Andyou can right-click on an area of Package Explorer, select "Clean up..." and configure that with a "Remove unnecessary casts" action.
而且你可以在Package Explorer中的区域单击鼠标右键,选择“清理......”并配置了“删除不必要的强制类型转换”的动作。
So basically this should be simple :)
所以基本上这应该很简单:)
回答by Bernard
You should probably use a tool to analyze your Java source code for potential problems (such as unnecessary casting).
您可能应该使用工具来分析您的 Java 源代码是否存在潜在问题(例如不必要的强制转换)。
Perhaps you can try PMD: http://pmd.sourceforge.net
也许你可以试试 PMD:http: //pmd.sourceforge.net
回答by musiKk
If you use Eclipse, this should be fairly easy. Right click the class/package/project and select Source- Clean Up....
如果您使用 Eclipse,这应该相当容易。右键单击类/包/项目并选择Source- Clean Up...。

