To prevent developers from using System.currentTimeMillis()
or new Date() (except through your SystemInfoService), you can automate the check using Checkstyle. Here's a simple way to set it up:
Add Checkstyle to Your Project: First, you need to add Checkstyle to your Maven build. In your pom.xml, add this plugin:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId>
<version>3.1.0</version>
<configuration>
<configLocation>src/main/resources/checkstyle.xml</configLocation>
<failOnViolation>true</failOnViolation>
</configuration>
</plugin>
Create a Checkstyle Configuration:
Then, create a checkstyle.xml file in src/main/resources
that will catch calls to System.currentTimeMillis()
and new Date():
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE module PUBLIC
"-//Checkstyle//DTD Checkstyle Configuration 1.3//EN"
"https://checkstyle.org/dtds/configuration_1_3.dtd">
<module name="Checker">
<module name="TreeWalker">
<!-- Block System.currentTimeMillis() -->
<module name="IllegalMethodCall">
<property name="illegalClassNames" value="java.lang.System"/>
<property name="illegalMethodNames" value="currentTimeMillis"/>
</module>
<!-- Block new Date() -->
<module name="IllegalMethodCall">
<property name="illegalClassNames" value="java.util.Date"/>
<property name="illegalMethodNames" value="<init>"/>
</module>
</module>
</module>
Run Checkstyle in CI/CD: To make sure the rule is always enforced, add Checkstyle to your CI/CD pipeline (like Jenkins, GitHub Actions, etc.). This will automatically flag any commits that use System.currentTimeMillis() or new Date().