简体   繁体   中英

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

I have the following piece of Java code:

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

The checkPrecondition call raises a runtime exception if chain is null, but Eclipse doesn't seem to "get this": it says chain.silence() is a possible null pointer access (warning). Question: How can I "tell" Eclipse that checkPrecondition() ensures that chain is not null, ie has the character of an assertion? I know that I can disable this warning, but I'd rather not do that, because in other situations, it might be justified.

Interestingly enough, when I remove the checkPrecondition() call, the warning disappears (which is precisely the case in which I'd expect to see it).

I use Eclipse 4.4.2 (32 bit) on Windows. Java VM is 1.3 (!). Update to newer versions of either is not currently an option.

You don't tell Eclipse, you have to produce a code in such a syntax and logic that the Java compiler will compile successfully and that the JVM will be able to execute.

It's normal that a runtime exception occurs. A variable value can only be checked at runtime, same for the null pointer (in fact it's the case in almost every language pretending to come from C and using something related to pointers and it was already the case before C).

You can solve this problem using two different approches, depending your style and the one used in your projet.

  • First comes the defensing way --> you consider that the subprogram should be killed before such an error occurs (null pointers errors cost a lot in the software industry).

     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(); } } 
  • The second way is offensive : the calling code should handle this and the subprocess doesn't have to crash anything !

     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; } 

Please note that I suppose the checkcondition method is returning a boolean and that its single argument should be an object from the Chain class.

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