How to prevent class compilation

I'm just wondering if it can be prevented so that my Java application does not compile if certain conditions were broken and somehow just throw a compilation error. (in my case, I want to check if the hashcode implementation among unique package implements unique values ​​for caching purposes). I know that this is possible by writing a maven plugin using reflection, but unfortunately this is not a solution for me.

+4
source share
3 answers
  • The situation you described is resolved using the unit test. A unit test may prevent your code from being built or delivered, but, of course, it cannot stop compiling it because it needs compiled code to work. They are very easy to configure and bind to build in Maven, also possible in Ant.

  • As far as I know, aspect-oriented programming can add compilation time constraints. This is briefly described in this answer here to the Java question I asked again. compilation time limit. Likewise, if AOP can force package dependencies, perhaps it can make class Foo depend on the Bar class, which is your situation, but I really don't know AOP, so a happy study.

  • Again, for simpler cases, you can simply add a precompilation step, even using the C preprocessor and the #error macro. But this is partly what AOP is.

  • You can add static statements so that the class fails at boot time, which is ahead of execution time (sort of), but later than compilation time. Improving download times. Again, unit tests are how this problem is actually resolved.

  • As described, you cannot cause compilation time to fail when calculating the runtime using pure Java.

+2
source

No, you cannot do such checks at compile time (assuming a regular compiler with javac ).

The usual way to do this is to have unit tests that run whenever you build (in any case, no one does a β€œmanual” compilation in real projects).

Having a build failure with failed tests is a very common scenario.

+5
source

You will need a compiler that supports checking your invariants; possibly an extensible compiler such as JastAddJ .

Most projects rely on either unit tests to verify behavior or static analysis after compilation using tools such as findbugs or Coverity .

It is possible that in a language such as Scala, you can encode the desired invariants in the type system, in which case the compiler will be able to verify that a particular subclass obeys the contract.

+1
source

Source: https://habr.com/ru/post/1488101/


All Articles