I do not mean the compile errors because I made a syntax mistake or whatever. In C++ we can create compile time errors based on conditions as in the following example:
template<int> struct CompileTimeError; template<> struct CompileTimeError<true> {}; #define STATIC_CHECK(expr, msg) { CompileTimeError<((expr) != 0)> ERROR_##msg; (void)ERROR_##msg; } int main(int argc, char* argv[]) { STATIC_CHECK(false, Compile_Time_Failure); return 0; }
In VS 2005 this will output:
------ Build started: Project: Test, Configuration: Debug Win32 ------ Compiling... Test.cpp f:\temp\test\test\test.cpp(17) : error C2079: 'ERROR_Compile_Time_Failure' uses undefined struct 'CompileTimeError<__formal>' with [ __formal=0 ] Build log was saved at 'file://f:\temp\Test\Test\Debug\BuildLog.htm' Test - 1 error(s), 0 warning(s) ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
Is there any way to achieve this in Java?
There is no way to do this in Java, not in the same way it works for you in C++.
You could perhaps use annotations, and run apt before or after compilation to check your annotations.
For example:
And then write your own AnnotationProcessorFactory that looked for @MyStaticCheck annotations, and does something with the arguments.
Note: I haven’t played too much with apt, but the documentation makes it looks like this is very do-able.