java namespace collisions

梦想的初衷 提交于 2020-01-05 07:42:12

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!