问题
I find myself frequently making the following error.
public class Foo{
Bar bar;
public void doSomething(){
Bar bar = makeNewBar();
// bla bla
}
}
where the error is that I want to set Foo's bar, not a local Bar. I.e, I should say bar = makeNewBar()
, not Bar bar = makeNewBar()
. Is there a compiler warning flag or something that can detect "namespace collisions" like this? If not, what's a good way to avoid this (short of not making the error, which is obviously the best option =p)?
回答1:
That's not really the job of the compiler but most IDE warn you with correct settings if you shadow a variable.
Using Eclipse, go to Preferences / Java / Compiler / Error/Warnings
and look for Name shadowing and conflicts
.
回答2:
Couldn't you use
this.bar = makeNewBar();
(That will be less confusing to the reader of the class also..)
(OR)
This URL shows that Eclipse can be configured to warn about declarations that hide class members:
http://help.eclipse.org/juno/index.jsp?topic=%2Forg.eclipse.jdt.doc.user%2Freference%2Fpreferences%2Fjava%2Fcompiler%2Fref-preferences-errors-warnings.htm
See the section on "Field declaration hides another field or variable"
The documentation states that this warning is defaulted (in ECLIPSE) to IGNORE, so you are right in that it would have to be explicitly set.
来源:https://stackoverflow.com/questions/14816554/java-namespace-collisions