简体   繁体   中英

Batch refactoring to make Java method arguments final

I'm looking around for a way to perform batch refactoring on a complete Java application. In this namely make method arguments final where it's not the case yet.

Does somebody in here knows about such a tool ? Or something that parses Java source and that can be extended with such changes.

You can do a bulk change in IntelliJ to change every field, local variable or parameter which can be final to be final.

Do a Code Analysis with the option, and "Apply Fix" globally, make sure it still compiles as it doesn't always get it 100% right in odd cases.

As Peter Lawrey suggests, IntelliJ does that.

Analyze -> Inspect code -> custom profile

There, in the "Code style issues" section, you have:

Field may be final

This inspection reports any fields which may safely be made final. A static field may 
be final if it is initialized in its declaration or in one static class initializer, but 
not both. A non-static field may be final if it is initialized in its declaration or in 
one non-static class initializer or in all constructors.
Powered by InspectionGadgets

Local variable or parameter can be final

This inspection reports parameters or local variables, found in the specified inspection
scope, that may have a final modifier added.

Use check boxes in the inspection options below, to define whether parameters or local
variables (or both) are to be reported.

That will propably only make final the variable that can safely be so but the ones that you're trying to spot will remain non-final. Still, it's a way to spot them.

I don't know of any such refactoring in Eclipse or NetBeans. But a decent regular expression replace would do the trick. In order to make sure you don't accidentally perform it in places where it shouldn't happen, you might want to confirm each replace manually. This might not really be feasible if you have hundreds of classes, though. In that case, doing the replace everywhere and then checking a diff with the older version could be of use.

Should any argument not be made final because it is overwritten, it'll become clear during compilation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM