确保具有特定注释的字段为“私有” [英] Ensure that fields with specific annotations are 'private'
问题描述
我们的代码中常见的错误是写
Very common mistake in our code is to write
@Mock Object object;
@InjectMocks Subject subject;
而不是
@Mock private Object object;
@InjectMocks private Subject subject;
这可以防止PMD / FindBugs / IntelliJ在字段未使用时发出警告,同时我们的代码审查也是让这个字段变为私有评论臃肿。
This prevents PMD/FindBugs/IntelliJ from issuing warning when the field becomes unused and also our code reviews are bloated with "make this field private" comments.
当具有特定注释的字段没有预期的可见性时,是否有任何静态分析规则在任何工具中发出警告?
Is there any static-analysis rule in any tool to warn when fields with specific annotations do not have expected visibility?
我找到了Checkstyle的 VisibilityModifier ,但是它标记所有非私有字段,而不仅仅是具有特定注释的字段。
I found Checkstyle's VisibilityModifier, but it marks all non-private fields, not just the ones with specific annotations.
推荐答案
您可以使用结构搜索IntelliJ IDEA中的检查。例如,使用如下模式:
You could use the Structural Search Inspection in IntelliJ IDEA. For example with a pattern like this:
@Mock @Modifier("packageLocal") $FieldType$ $FieldName$ = $Init$;
FieldType:min:1,max:1
FieldName:min:1 ,max:1
初始值:min:0,max:1
FieldType: min: 1, max: 1
FieldName: min: 1, max: 1
Init: min: 0, max: 1
这篇关于确保具有特定注释的字段为“私有”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!