繁体   English   中英

在检查潜在的空指针时如何配置Eclipse(Java)以识别自定义断言

[英]How to configure Eclipse (Java) to recognize custom assertion when checking against potential null pointer

我有以下一段Java代码:

public void silence(final Object key) {
    final Chain chain = (Chain)getChain(key);
    checkPrecondition(chain != null);
    chain.silence();
  }

如果chain为null,则checkPrecondition调用会引发运行时异常,但是Eclipse似乎没有“得到”:它说chain.silence()是可能的null指针访问(警告)。 问题:我如何“告诉” Eclipse checkPrecondition()确保链不为空,即具有断言的字符? 我知道我可以禁用此警告,但是我不希望这样做,因为在其他情况下,它可能是有道理的。

有趣的是,当我删除checkPrecondition()调用时,警告消失了(这正是我期望看到的情况)。

我在Windows上使用Eclipse 4.4.2(32位)。 Java VM是1.3(!)。 当前没有选择更新到任何一个的较新版本。

您无需告诉Eclipse,您必须以一种语法和逻辑生成代码,以使Java编译器能够成功编译并且JVM能够执行。

发生运行时异常是正常的。 只能在运行时检查变量值,这与空指针相同(实际上,几乎每种语言都假装来自C并使用与指针相关的东西都是这种情况,C之前就是这种情况)。

您可以使用两种不同的方法来解决此问题,具体取决于您的样式和在Projet中使用的方法。

  • 首先是防御方法->您认为应该在发生此类错误之前将子程序杀死(空指针错误在软件行业造成很大的损失)。

     public void silence(final Object key) { if (key == null) { throw new IllegalArgumentException("Key should not be null."); } Object oChain = getChain(key); if (oChain == null || !(oChain instanceof Chain)) { throw new IllegalArgumentException("Key should be mapped to an object from the Chain class type."); } Chain chain = (Chain)oChain; if(checkPrecondition(chain)) { chain.silence(); } } 
  • 第二种方法是令人反感的:调用代码应处理此问题,并且子进程不必崩溃任何东西!

     public boolean silence(final Object key) { if (key == null) return false; Object oChain = getChain(key); if (oChain == null || !(oChain instanceof Chain)) return false; Chain chain = (Chain)oChain; if(!checkPrecondition(chain)) return false; chain.silence(); return true; } 

请注意 ,我假设checkcondition方法返回一个布尔值,并且它的单个参数应该是Chain类中的一个对象。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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