Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assert something at compile time in Java?

Tags:

java

Sometimes data structures should have certain relationships that can't be directly described in Java, but that are good to check as early as possible when code is edited. Classic examples are that an array is big enough or that enums in different modules have corresponding members.

BOOST provides a fine "static assert" facility in C++ that even provides half-decent errors when assertions fail; does anyone know how to build a compile-time assertion facility in Java?

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

like image 202
James Avatar asked Jun 15 '09 21:06

James


People also ask

What does assert () do in Java?

assert is a Java keyword used to define an assert statement. An assert statement is used to declare an expected boolean condition in a program. If the program is running with assertions enabled, then the condition is checked at runtime. If the condition is false, the Java runtime system throws an AssertionError .

How do you do assert in Java?

An assertion is made using the assert keyword. Its syntax is: assert condition; Here, condition is a boolean expression that we assume to be true when the program executes.

Is static assert compile time?

The _Static_assert keyword, and the static_assert macro, both test a software assertion at compile time. They can be used at global or function scope. In contrast, the assert macro and _assert and _wassert functions test a software assertion at runtime and incur a runtime cost.

Is assert compile time?

assert(f != must be done at run time. However, an assertion that tests the value of a constant expression, such as the size or offset of a structure member, can be done at compile time.


2 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 in)
  • Cobertura/EMMA (for Code coverage).

A combination of these and good unit tests will catch the low hanging fruit (and some of the higher stuff as well)

like image 184
Fortyrunner Avatar answered Sep 26 '22 17:09

Fortyrunner


Incremental compilers that come as part of IDEs like Eclipse can be configured to throw warnings or errors on finding code that is legal java, but may cause problems at runtime. You can ratchet these settings up as far as you like, although it may start to get invasive and annoying.

like image 35
skaffman Avatar answered Sep 26 '22 17:09

skaffman