How to assert something at compile time in Java?

Sometimes data structures must have certain relationships that cannot be directly described in Java, but it is good to check as early as possible when the code is edited. Classical examples are that the array is large enough or that the enumerations in different modules have corresponding elements.

BOOST provides an excellent C ++ "static assertion" facility that even provides semi-decent errors when assertions fail; Does anyone know how to build a compile-time approval tool in Java?

Edit: I just saw a great example: this class from Eclipse has two constant arrays that are supposed to be the same length. If this was my code, I would like the compiler to tell me if they have different lengths.

+7
java
source share
3 answers

There are a number of tools you can use.

  • PMD
  • Checkstyle
  • Findbugs
  • Validate methods in Jakarta Commons-lang (we use this instead of assert and leave it)
  • Cobertura / EMMA (for code coverage).

A combination of these and good unit tests will catch low-hanging fruits (and some of the taller things too)

+7
source share

The incremental compilers that are part of the IDE, such as Eclipse, can be configured to throw warnings or errors when looking for code that is legal java but can cause runtime problems. You can store these settings as you like, although it can start to be aggressive and annoying.

+2
source share

You can use annotations.

See Which @NotNull Java Annotation should I use? for parameters.

See JSR-308 and JSR-305 for the future of java.

+1
source share

All Articles