如何在SonarQube v8.4.0.35506中仅运行指定单条Java规则?
Got it, let's sort this out—you don't need to manually ignore every single rule except your target one. There are two straightforward approaches to run only that specific rule, depending on whether you want a reusable setup or a one-off scan.
Approach 1: Create a Custom Quality Profile (Reusable)
This is the best long-term solution if you plan to run this rule regularly for your project or multiple projects.
- Head to your SonarQube dashboard and click the Quality Profiles tab at the top.
- Use the language filter to select Java, then find the default profile your project uses (usually "Sonar way").
- Click the More actions (three-dot menu) next to that profile, then choose Copy. Give your new profile a clear name like "Java - Only Unused Assignments" and save it.
- Open your new custom profile, then go to the Rules tab.
- First, disable all pre-enabled rules: Click the Bulk Change button at the top, select Disable all rules in this profile, and confirm the action.
- Now search for your target rule: Either type the full name
"Unused assignments should be removed"in the search bar, or use its rule keyjava:S1854(searching by key is faster and more accurate). - Once you find the rule, click the Activate button on its right side to enable it in your custom profile.
- Finally, go to your project's settings page, find the Quality Profile dropdown, select your new custom profile, and save the changes. Now every scan for this project will only run that single rule.
Approach 2: Run a One-Off Scan with Command Line Parameters
If you just need to run this rule once (for testing or a quick check), you can skip creating a custom profile and specify the rule directly in your SonarScanner command:
Option A: Command Line Argument
Add the -Dsonar.rules parameter when launching SonarScanner:
sonar-scanner -Dsonar.projectKey=your-project-key -Dsonar.sources=./src -Dsonar.rules=java:S1854
Option B: Update sonar-project.properties
Add this line to your project's sonar-project.properties file before running the scan:
sonar.rules=java:S1854
This will force the scan to only execute the java:S1854 rule (which maps to "Unused assignments should be removed").
Both methods work perfectly in SonarQube 8.4.0, so pick whichever fits your needs better!
内容的提问来源于stack exchange,提问作者Idriss Riouak

