Improve error messages for synthetic/anonymous class violations #1552
+97
−5
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Description
Improves error messages when ArchUnit rules fail on synthetic or anonymous classes generated by the compiler. New users are often confused when rules fail on classes like
MyService$1that they didn't write, with no clear guidance on how to resolve the issue.Problem
As reported in #1509 and #1019, users encounter confusing error messages like:
This happens when the Java compiler generates synthetic classes for:
Users spend significant time debugging these "violations" even though they aren't actual architectural issues in their source code.
Solution
This PR adds helpful hints to error messages when rules fail on synthetic or anonymous classes:
Before:
After:
The hint only appears when relevant—regular class violations remain unchanged.
Implementation Details
Why Check Both SYNTHETIC and Anonymous?
Synthetic classes: Compiler-generated (e.g., enum switch maps defined in JLS 13.1.7)
ACC_SYNTHETICflag in bytecodeMyClass$1from enum switchesAnonymous classes: Explicitly created in source but may violate naming rules
isAnonymousClass()new Runnable() {}SYNTHETICcheck doesn't work butareNotAnonymousClasses()doesChanges Made
Core Implementation (
ArchConditions.java):haveWithHint()method that creates customArchConditionwith hint supportisSyntheticOrAnonymous()helper to detect both synthetic and anonymous classeshaveWithHint():haveSimpleNameStartingWith()haveSimpleNameContaining()haveSimpleNameEndingWith()Unit Tests (
ClassesShouldTest.java):NestedClassWithSomeMoreClasses.getAnonymousClass()for testingIntegration Tests:
ExpectedNaming.javato handle hint messagesExamplesIntegrationTest.javato include expected hint linesUseCaseOneThreeController$1(synthetic class from enum switch)Compatibility
isAnonymousClass()available since Java 1.5JavaModifier.SYNTHETICavailable since Java 1.5./gradlew clean build -PallTests✅ passesTesting
Test Coverage
BUILD SUCCESSFULwith all testsTest Results
Related Issues
Resolves #1509
Relates to #1019
Checklist
./gradlew clean build -PallTests)git commit -s)