Home > OS >  Is there a way to make var a compile-time error in Maven?
Is there a way to make var a compile-time error in Maven?

Time:02-02

We're updating to us Java 17. Is there a way in Maven to make it so that using var creates a compile-time error without compiling for an older version of java? In other words, I don't want to have to tell Maven to compile for 1.8 or the like.

I'd also prefer not to use an IDE centric solution since we don't all use the same IDE.

CodePudding user response:

In general consider using static analyzer of your code that runs as a plugin. You can define a rule to fail the build once var is observed in the code.

CodePudding user response:

You can use Checkstyle's IllegalType check. Checkstyle has a Maven plugin.

The relevant part of the XML config would look like:

...
<module name="IllegalType">
  <property name="illegalClassNames" value="var"/>
</module>
...

Bit funny that the property is called "illegalClassNames", but I tested and it worked, as Checkstyle's maintainer said it would.

CodePudding user response:

Like Mark said, this is a job for a static code analyzer. I would use Checkstyle, which can easily be integrated with Maven.

I think Checkstyle does not have a built-in rule for var, but you can use the MatchXpath module to achieve what you want. In fact, the example on the website does the opposite, requiring that all variables use var. To get the result you want, you should be able to simply invert the second part of the rule:

<module name="MatchXpath">
  <property name="query" value="//VARIABLE_DEF[./ASSIGN/EXPR/LITERAL_NEW
          and (./TYPE/IDENT[@text='var'])]"/>
  <message key="matchxpath.match" value="'var' not allowed"/>
</module>
  • Related