Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent class compilation

Tags:

java

I'm just wondering if its possible to prevent my Java app to compile if certain conditions are broken and just throw compile error somehow. ( in my case i want to check if hashcode implementations among certain package returns unique values, for caching purposes ) I know it is possible by writing maven plugin using reflection, but unfortunatelly it's not a solution for me.

like image 745
kookee Avatar asked Feb 16 '23 03:02

kookee


2 Answers

No, you can't do checks like this during compilation (assuming a normal compile with javac).

The usual way to do this is to have unit tests that are executed whenever you make a build (no one really does "manual" compiles in real projects, anyway).

Having the build break with an error when a tests fails is a very common scenario.

like image 70
Joachim Sauer Avatar answered Mar 08 '23 11:03

Joachim Sauer


  1. The situation you described is solved by a unit test. A unit test can prevent your code from being built or delivered, but of course it can't stop it from being compiled because it needs compiled code to work on. These are very easy to set up and bind to building in Maven, also possible in Ant.

  2. To my knowledge aspect-oriented programming can add compile time constraints. This was briefly covered in this answer here, to a Java question I asked re. a compile-time constraint. Analogizing, if AOP can enforce package dependencies, perhaps it can force class Foo to depend on class Bar, which is your situation - but I don't actually know AOP, so happy researching.

  3. Again, for simpler cases, you could actually just add a precompiling step, even using a C preprocessor and the #error macro. But this is partly what AOP is.

  4. You can add static asserts so that the class fails at load time, which is ahead of runtime (sort of) but later than compile time. An improvement over load time. Again, unit tests are how this problem is actually solved.

  5. As described, you cannot cause a compile-time failure by a runtime computation using pure Java.

like image 37
djechlin Avatar answered Mar 08 '23 10:03

djechlin