Ban a spesific function/constructor #12975
-
Basically I'm looking at banning the specific Thread constructor Thread(Runnable task), to force people to name their threads (ie: use Thread(Runnable task, String name)). Currently I'm attempting to achieve this with regex, but it's pretty tricky as the runnable can be declared inline. Any ideas? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 3 replies
-
@VirtualTim it sounds like MatchXPath could be perfect for your use case; we can help you to formulate an XPath expression. Please share an example of
to make sure we can cover all cases. |
Beta Was this translation helpful? Give feedback.
-
@VirtualTim this should work for you: ➜ src cat Test.java
public class Test {
void inlineGood() {
new Thread(new Runnable() {
@Override
public void run() {}
}, "thread name").start();
}
void inlineBad() {
new Thread(new Runnable() { // violation
@Override
public void run() {}
}).start();
}
void goodThreads() {
new Thread(m(), "thread name").start();
new Thread(() -> m(), "thread name").start();
}
void badThreads() {
new Thread(m()).start(); // violation
new Thread(() -> m()).start(); // violation
}
Runnable m() {
return System.out::println;
}
}
➜ src cat config.xml
<?xml version="1.0"?>
<!DOCTYPE module PUBLIC
"-//Checkstyle//DTD Checkstyle Configuration 1.3//EN"
"https://checkstyle.org/dtds/configuration_1_3.dtd">
<module name="Checker">
<property name="severity" value="error"/>
<property name="fileExtensions" value="java, properties, xml"/>
<module name="TreeWalker">
<module name="MatchXpath">
<property name="query" value="//LITERAL_NEW
[./IDENT[@text='Thread'] and .[2 > count(./ELIST/*)]]"/>
<message key="matchxpath.match"
value="Thread should be named via 'Thread(task, name)' constructor."/>
</module>
</module>
</module>
➜ src java -jar checkstyle-10.7.0-all.jar -c config.xml Test.java
Starting audit...
[ERROR] /home/nick/IdeaProjects/tester/src/Test.java:10:9: Thread should be named via Thread(task, name) constructor. [MatchXpath]
[ERROR] /home/nick/IdeaProjects/tester/src/Test.java:22:9: Thread should be named via Thread(task, name) constructor. [MatchXpath]
[ERROR] /home/nick/IdeaProjects/tester/src/Test.java:23:9: Thread should be named via Thread(task, name) constructor. [MatchXpath]
Audit done.
Checkstyle ends with 3 errors. |
Beta Was this translation helpful? Give feedback.
@VirtualTim this should work for you: