IDEA Inspections详解


之前用Eclipse的时候就特别喜欢琢磨eclipse的warning级别(黄叹号),以期待coding出最模范的代码。

换成IDEA后,发现其代码检查功能更加复杂,遂仔细琢磨分析,寻找最适合自己的配置

Abstraction issues

Title

默认

建议

描述

'instance of' a concrete class

 

warning

instance of一般判断是否是一个接口或者抽象类的实例

'instance of' check for this

 

warning 

使用this肯定知道是哪个Class

interface method clashes with method in 'java.lang.Object'

warning

warning

接口定义的方法名和Object的方法冲突,如clone方法

Magic number

 

warning

不允许任何魔法值(即未经定义的常量)直接出现在代码中 ,参考阿里规范

'Optional' used as field or parameter type

warning

warning

java.util.Optional一般用作防空指针,定义成成员变量或者参数比较奇怪

Overly strong type cast

 

warning

高强强制类型转换,有时候我们强转List即可却强转成ArrayList

Assignment issues 

Title

默认

建议

描述

Assignment to for 'loop' parameter

 

warning

在for循环中改变了循环的参数

Constructor assigns value to field defined in superclass

 

warning

在构造方法中对父类成员变量赋值,这样做不合理,应该调用父类构造方法

Class Metrics

Title

默认

建议

描述

Class with too many constructors

 

warning

类的构造方法过多(默认限制5个)

Class structure

Title

默认

建议

描述

Class name differs from file name

 

warning

类名和文件名不同

Field can be local

warning

warning

成员变量可以声明成final的

No-op method in abstract class

 

warning

抽象类中的空方法没有被声明成abstract,比较少见

Parameter can be local

warning

warning

参数可以声明成局部变量

'private' method declared final

warning

warning

私有方法被声明成final的了,冗余

'protected' member in final class

 

warning

定义成final的类无法被继承,protected的使用不正确

'static' method declared final

warning

warning

静态方法被定义成final,无意义

Code maturity

Title

默认

建议

描述

Call to printStackTrace()

 

warning

成熟的代码应该使用log

Call to Thread.dumpStack

 

warning

静态dumpstack()方法提供一个new exception ("stack trace").printstacktrace ()的封装,打印一个追踪当前线程的堆栈,调试用。

Deprecated API usage

 warning

warning

使用了过时的API

Deprecated member is still used

 warning

warning

使用了过时的member

Throwable printed to system.out

 warning

warning

用system.out来print异常

Usage of API marked as removal

 error

error

使用了被@Deprecated(forRemoval=true) 标记的方法

Use of absolute collection type

 

warning

使用了java.util.Vector or java.util.Hashtable这些不推荐使用的类

Use of System.out or System.err

 

warning

使用了System.out or System.err,用log替代

Code style issues

Title

默认

建议

描述

Blocker marker comment

 

warning

注释位置不合理

while (i < 10) {
i++;
} // end while参考阿里规范,写在while上方

C-style array declaration

No high lighting,only fix 

warning

C语言风格的数组声明

public String process(String value[])[] {
return value;
}

Class explicitly extends java.lang.Object

warning

warning

直接声明一个类继承了Object,无意义

Control flow statement without braces

No high lighting,only fix 

warning

条件或者循环语句括号没打好

(expression).equals("literal")rather than("literal").equals(expression)

 

warning

减少空指针的好习惯

indexOf expression is replacable with contains

 

warning

Reports any List.indexOf() expressions which can be replaced with the method List.contains(). 

Missorted modifiers

 

warning

修饰词顺序不符合规范 

Multiple variables in one declaration

 

warning

一行代码声明了多个变量

Null value for Optional type

warning

warning

Optional本身常用来防空指针,不应为null

Raw type can be generic

No high lighting,only fix    

warning

可以使用泛型的地方未使用

Redundant no-arg constructor

 

warning

多余的无参构造方法

size==0 replacable with isEmpty

 

warning

很实用,判断list非空isEmpty一目了然

Subsequent steps can be fused into Stream API chain

 warning

warning

链式编程优化Detects when some transformations are performed on Stream API result which could be incorporated into the Stream API call chain directly. E.g.:
List<String> list = stream.collect(Collectors.toList());
list.sort(null);
return list.toArray(new String[list.size()]);
Could be converted to
return stream.sorted().toArray(String[]::new);

Type parameter explicitly extends java.lang.Object

warning

warning

参数显式继承Object 

Unnessarily null check before equals call

 

warning

多余的空指针校验

Unnessarily String.valueOf()

warning

warning

如StringBuffer.append(String.valueOf(1));

Unnessarily enum modifier

warning

warning

枚举多余的修饰词

Unnessarily interface modifier

warning

warning

接口声明中多余的修饰词

Unnessarily semicolon

warning

warning

多余的分号

Variables of different types in one declaration

 

warning

一行声明多个不同类型的变量,String s = "", array[];

Control flow issues

Title

默认

建议

描述

Boolean expression could be replaced with conditional expression

 

warning

Boolean类型表达式优化

Reports any boolean expressions which can be expressed more compactly, and arguably more clearly, as a conditional expression. Take for example the following expression:

a && b || !a && c;

which may be expressed as:

a ? b : c;

Conditional can be pushed inside branch expression

No high lighting,only fix    

warning

条件表达式优化

Reports conditional expressions with then and else branches so similar that the conditional expression can be pushed inside, thereby shortening the code.

For example the following conditional expression:

condition ? message("value: " + 1) : message("value: " + 2)

Can be pushed inside and transformed into:

message("value: " + (condition ? 1 : 2))

Conditional expression with negated condition

warning

warning

Reports conditional expressions of the form true?result1:result2 or false?result1:result2. These expressions sometimes occur as the result of automatic refactorings, and may obviously be simplified.

default not last case in switch statement

 

warning

在switch中,default不在最后

double negation

warning

warning

双重否定

Reports double negation.

For example:

if (!!functionCall())

duplicate condition in if statement

 

warning

if中出现了重复的条件

duplicate condition on && or ||

 

warning

条件重复

fallthrough in switch statement

 

warning

swich中未使用break

idempotent loop body

warning

warning

幂等循环体,不会被结束

int suffix = 1;

String name = baseName;

while(names.contains(name)) {

name = baseName + suffix; // error: suffix is not updated making loop body idempotent

}

if statement could be replaced with conditional expression

 

warning

if语句可以换三元运算符

if (foo == null) {

bar = null;

} else {

bar = foo.get();

}

may be expressed as:

bar = foo == null ? null : foo.get();

if statement with negated condition

 

warning

if的条件是否定,可以调换if else顺序

infinite loop statement

 

warning

无限循环语句

loop statement that does not loop

warning

warning

循环语句不会启动

loop variable not updated inside loop

warning

warning

循环标记变量在循环中不改变

move condition to loop

warning

warning

循环优化

while(true) { if(i == 23) break; i++; }

Will be replaced with:

while(i != 23) { i++; }

negated equality expression

 

warning

!(i == 1)

pointless indexOf comparison

 

warning

indexOf>-1则无意义

pointless boolean expression

warning

warning

无意义的boolean表达式

redundant else

No high lighting,only fix    

warning

冗余的else

redundant if statement

warning

warning

多余的if

For example:

if (foo()) {

return true;

} else {

return false;

}

can be simplified to

return foo();

redundant conditional expression

warning

warning

多余的三元运算符

Example Replacement

condition ? true : false condition

condition ? false : true !condition

value == null ? null : value value

result != 0 ? result : 0 result

a == b ? a : b b

 

simplifiable boolean expression

warning

warning

boolean表达式可以简化

Reports boolean expressions of the form !(foo ^ bar) and (foo && bar) || !foo. Such expressions may be safely simplified to foo == bar and !foo || bar respectively.

simplifiable conditional expression

warning

warning

可简化的三元运算符

Reports conditional expressions of the following form

condition ? true : foo

condition ? false : foo

condition ? foo : !foo

condition ? !foo : foo

These expressions may respectively be safely simplified to

condition || foo

!condition && foo

condition == foo

condition != foo

switch statement without default branch

 

warning

switch缺少default

Unnessary null check before instanceof expression or call

warning

warning

instanceof无需校验null

Here is an example of a violation:

if (x != null && x instanceof String) { ... }

The quickfix changes this code to:

if (x instanceof String) { ... }

Data flow

Title

默认

建议

描述

boolean method is always inverted

warning

warning

总是使用反值

For example:

class C {

boolean inverted() {

return true;

}

void f() {

if (!inverted()) {

return;

}

}

boolean member = !inverted();

}

 

redundant local variable

warning

warning

多余局部变量

Declaration redundancy

Title

默认

建议

描述

Access static via instance reference

warning

warning

通过实例引用静态成员

Actual method parameter is the same constant

warning

warning

方法参数总是同一个常量

Collector can be simplified

warning

warning

lambda表达式根据场景简化

Declaration access can be weaker

warning

warning

可以定义更低的访问权限public->protected->default->private

Declaration can have final modifier

warning

声明可以加上final

Default annotation parameter value

warning

warning

使用注解的时候value传了默认值,可以隐藏

Duplicate throws

warning

warning

重复抛异常

Empty method

warning

空方法

Functional expression can be folded

warning

warning

This inspection reports method references or lambda expressions which point to a method of their own functional interface type and hence can be replaced with their qualifiers, like

SwingUtilities.invokeLater(r::run);

SwingUtilities.invokeAndWait(() -> r.run());

can be replaced with

SwingUtilities.invokeLater(r);

SwingUtilities.invokeAndWait(r);

Method can be void

warning

warning

方法可以声明成void的

Method returns the same value

warning

warning

方法返回值总是相同

Null-check method is called with obviously non-null argument

warning

warning

方法参数明显非空,则空指针校验冗余

redundant requires statement in module-info

warning

warning

The inspection detects a situation where Java 9 module A requires Java 9 module B, but A doesn't use any package from B. Also, requiring the module 'java.base' is redundant.

The fix deletes the 'requires' directive for such redundant dependencies. If the deleted dependency re-exported modules that are actually used, the fix adds 'requires' directive for these modules.

redundant close

warning

warning

冗余的close方法调用

redundant step in stream or optional call chain

warning

warning

lambda表达式简化场景:

Reports useless Stream or Optional calls like map(x -> x) or filter(x -> true), useless sorted or distinct.

redundant throw clause

warning

warning

抛出了不会抛出的异常

remove redundant lambda parameter types

No high lighting,only fix    

warning

优化lambda参数自动推测

Example:

Map<String, Integer> map = ...

map.forEach((String s, Integer i) -> log.info(s + "=" + i));

Simplify optional chains

warning

warning

优化optional链

This inspection warns about Optional call chains which could be simplified. Here are some examples of possible simplifications:

optional.map(x -> true).orElse(false) → optional.isPresent()

optional.map(x -> Optional.of(x.trim())).orElseGet(Optional::empty) → optional.map(String::trim)

optional.map(x -> (String)x).orElse(null) → (String) optional.orElse(null)

Optional.ofNullable(optional.orElse(null)) → optional

val = optional.orElse(null); val != null ? val : defaultExpr → optional.orElse(defaultExpr)

val = optional.orElse(null); if(val != null) expr(val) → optional.ifPresent(val -> expr(val))

simplify stream API call chains

warning

warning

lambda表达式优化

The following call chains are replaced by this inspection:

collection.stream().forEach() → collection.forEach()

collection.stream().collect(toList/toSet/toCollection()) → new CollectionType<>(collection)

collection.stream().toArray() → collection.toArray()

Arrays.asList().stream() → Arrays.stream() or Stream.of()

IntStream.range(0, array.length).mapToObj(idx -> array[idx]) → Arrays.stream(array)

IntStream.range(0, list.size()).mapToObj(idx -> list.get(idx)) → list.stream()

Collections.singleton().stream() → Stream.of()

Collections.emptyList().stream() → Stream.empty()

stream.filter().findFirst().isPresent() → stream.anyMatch()

stream.collect(counting()) → stream.count()

stream.collect(maxBy()) → stream.max()

stream.collect(mapping()) → stream.map().collect()

stream.collect(reducing()) → stream.reduce()

stream.collect(summingInt()) → stream.mapToInt().sum()

stream.mapToObj(x -> x) → stream.boxed()

stream.map(x -> {...; return x;}) → stream.peek(x -> ...)

!stream.anyMatch() → stream.noneMatch()

!stream.anyMatch(x -> !(...)) → stream.allMatch()

stream.map().anyMatch(Boolean::booleanValue) -> stream.anyMatch()

IntStream.range(expr1, expr2).mapToObj(x -> array[x]) -> Arrays.stream(array, expr1, expr2)

Collection.nCopies(count, ...) -> Stream.generate().limit(count)

stream.sorted(comparator).findFirst() -> Stream.min(comparator)

unnecessary module dependency

warning

warning

无用模块依赖

unused declaration

warning

warning

无用的声明

unused label

warning

warning

无用标签

variable assigned to itself

warning

warning

a=a

Error handling

Title

默认

建议

描述

Catch block may ignore exception

warning

warning

捕获了异常没有处理

caught exception is immediately rethrown

warning

warning

捕获了未处理重新抛出的异常

continue or break inside finally block

warning

warning

finally代码块含有continue和break关键字

empty finally block

warning

warning

空finally块

empty try block

warning

warning

空try块

finally block can not complete normally

warning

warning

Reports finally blocks which can not complete normally.

instanceof on catch parameter

 

warning

使用instanceof来区分异常不如使用多个catch块

Nested try statement

 

warning

嵌套try

return inside finally block

warning

warning

finally中return

throw inside finally block

warning

warning

finally块中抛异常

Inheritance issues

Title

默认

建议

描述

Class extends annotation interface

warning

warnijng

Reports any classes declared as implementing or extending an annotation interface. While it is legal to extend an annotation interface, it is often done by accident, and the result won't be usable as an annotation.

final declaration can't be overridden at runtime

error

error

final不能被覆写

missing @override annotation

warning

warning

缺少@override注解

Java language level migration aids

Title

默认

建议

描述

for loop replacable with foreach

warning

warning

for循环用foreach形式写,减少.get(index)

indexOf expression is replacable with contains

warning

warning

部分场景,只判断是否包含可以用contains

StringBuffer may be StringBuilder

warning

warning

StringBuilder在不考虑线程安全情况下性能更好

Unnecessary boxing

warning

warning

多余装箱操作

Unnecessary unboxing

warning

warning

多余拆箱操作

while loop replacable with foreach

warning

warning

while循环用foreach改写

Explicit type can be replaced with <>

warning

warning

泛型可以隐藏右边的type

identical catch branches in try statement

warning

warning

多个catch同样处理可以合并

possible heap pollution from parameterized vararg type

warning

warning

This inspection reports all methods with variable arity which can be annotated as @SafeVarargs. @SafeVarargs annotation suppresses unchecked warnings about parameterized array creation at call sites.

try finally replacable with try with resources

warning

Before Java 7, the usual pattern was something like this:

Connection con = null; PreparedStatement prep = null; try{ con = getConnection(); prep = prep.prepareStatement("Update ..."); ... con.commit(); } catch (SQLException e){ con.rollback(); throw e; } finally{ if (prep != null) prep.close(); if (con != null) con.close(); }

With Java 7 you can go for:

try(Connection con = getConnection(); PreparedStatement prep = con.prepareConnection("Update ..."){ ... con.commit(); }

Numberic issues

Title

默认

建议

描述

call to BigDecimal method without a rounding mode argument

warning

warning

使用BigDecimal注意选择rounding mode

divdide by zero

warning

error

除零

equals called on java.math.BigDecimal

 

warning

使用compareTo

long literal ending with l instead of L

warning

warning

long类型以L结尾避免看成1

Number constructor with primitive argument

warning

warning

用.valueOf替代

Numeric overflow

warning

warning

This inspection checks for expressions which overflow during computation, i.e.:       a = 1.0/0.0;

Octal integer

warning

warning

使用八进制字符串容易出错Reports octal integer literals. Some coding standards prohibit the use of octal literals, as they may be easily confused with decimal literals.

Pointless arithmetic expression

warning

warning

无效算式

Performance

Title

默认

建议

描述

Boolean constructor call

warning

warning

new Boolean object比较鬼畜

Boxing of already boxed value

warning

warning

重复装箱

Call to Arrays.asList with too few arguments

warning

warning

0元素和1元素有更好的选择

Collections.singletonList() or Collections.emptyList() which will save some memory.

class initializer may be static

warning

warning

Reports any class initializers which may safely be made static. A class initializer may be static if it does not reference any of its class' non static methods and non static fields.

Collection.toArray call style

warning

warning

集合转成数组推荐using a pre-sized array (like c.toArray(new String[c.size()])) or using an empty array (like c.toArray(new String[0]).

Instantiating object to get Class Object

warning

warning

一些场景获取class直接用class名字就好了,无需实例对象.getClass

Manual array copy

warning

warning

复制数组推荐System.arraycopy().

Manual array to collection copy

warning

warning

数组转集合推荐Collection.addAll(Arrays.asList()) or Collections.addAll().

redundant Collection.addAll call

warning

warning

Set<String> set = new HashSet<>();

set.addAll(Arrays.asList("alpha", "beta", "gamma"));

can be replaced with:

Set<String> set = new HashSet<>(Arrays.asList("alpha", "beta", "gamma"));

redundant call to String.format

warning

warning

使用String.format缺无参数

redundant String constructor call

warning

warning

声明String无需使用构造方法

Replace inefficient Stream API call chains ending with count()

warning

warning

如果只需要取size直接.size()就好了Collection.stream().count() → Collection.size()

Single charactor string argument in String.indexOf call

 

warning

单字符串String无需indexOf直接equals即可

String concatenation as argument to StringBuilder.append call

warning

warning

StringBuilder/Buffer append时,不应当使用拼接字符串参数

String concatenation in loop

warning

warning

循环中拼接字符串,用StringBuilder/Buffer

String.equals("")

 

warning

直接.length==0,可能null则使用StringUtils.isEmpty

unnecessary temporary object in conversion from String

warning

warning

For example:

new Integer("3").intValue()

will be reported, and can be automatically converted to:

Integer.valueOf("3")

unnecessary temporary object in conversion to String

warning

warning

For example:

new Integer(3).toString()

will be reported, and can be automatically converted to:

Integer.toString(3)

 

use bulk operation instead of iteration

warning

warning

可以addAll则避免递归add

Probable bugs

Title

默认

建议

描述

Array comparison using == instead of Array.equals

 

warning

正确比较数组每个元素相等的方法Arrays.equals()

Call to toString on array

warning

warning

输出数组元素不能直接toString

Call to default toString

 

warning

未覆写ToString时使用只会打印地址

Call to String.replaceAll(".",...)

warning

warning

注意正则表达式,正确做法replaceAll("\.", ...)

Collection added to itself

warning

Reports cases where the argument of a method call on a java.util.Collection or java.util.Map is the collection or map itself. This includes adding a collection to itself, which can lead to a java.lang.StackOverflowError when, for example, calling hashCode() on the self-containing collection.

Confusing argument to varargs method

warning

warning

For example System.out.printf("%s", null)

Confusing primitive array argument to varargs method

warning

warning

System.out.printf("%s", new int[]{1, 2, 3}) )

equals and hashCode are not pared

 

warning

两个对象如果不相等,hashCode不强制要求不一样,但是如果能保证不一样,对哈希的效率会比较有帮助最重要的是第二点,相等的对象必须有相同的hashCode,由于默认的hashCode方法针对每一个对象返回一个固定的随机值(有的实现是根据对象地址返回值,相当于每一个对象对应一个固定的随机值),所以当我们使用equals方法的同时,必须override(重写)hashCode方法,以满足这一点。

equals between objects of inconvertible types

warning

warning

类型不同equals无意义

equals called on array

warning

warning

比较数组使用Arrays工具类

Use Arrays.equals() to compare the contents of two arrays or Arrays.deepEquals() to compare the content of two multi-dimensional arrays.

equals called on itself

warning

warning

自己跟自己比=true

equals called on StringBuilder

warning

warning

StringBuilder并没有重写equals方法

equals method does not check class of parameter

warning

warning

equals方法中注意检查Class,如String.equals

public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
String anotherString = (String)anObject;
int n = value.length;
if (n == anotherString.value.length) {
char v1[] = value;
char v2[] = anotherString.value;
int i = 0;
while (n-- != 0) {
if (v1[i] != v2[i])
return false;
i++;
}
return true;
}
}
return false;
}

infinite recursion

warning

warning

无限递归

Magic Constant

warning

warning

魔法值

new Font("Arial", 2) -> new Font("Arial", Font.ITALIC)

Math.random cast to int

warning

warning

Math.random()返回0-1的小数

Number comparison using == instead of equals

warning

warning

包装类比较注意用equals

Object comparison using == instead of equals

No high lighting,only fix    

warning

比较对象相等一般不是要比较地址

Object.equals(null)

warning

warning

永远false

overwritten map or set element

warning

warning

map.put("A", 1);

map.put("B", 2);

map.put("C", 3);

map.put("D", 4);

map.put("A", 5); // duplicating key "A", overwrites previously written entry

statement with empty body

warning

warning

空语句

unused assignment

warning

warning

无用赋值

wrong package statement

error

error

错误包声明

Verbose or redundant code constructs

Title

默认

建议

描述

excessive lambda usage

warning

warning

过度lambda使用

For example, Optional.orElseGet(() -> null) can be replaced with Optional.orElse(null).

redundant collection operation

warning

warning

多余集合操作

Arrays.asList(array).subList(0, 10).toArray(new String[0]) could be simplified to Arrays.copyOfRange(array, 0, 10) or collection.containsAll(singletonList("x")) could be simplified to collection.contains("x").

redundant String operation

warning

warning

多余字符串操作

Reports a variety of redundant String-related operations like calling String.toString() or String.substring(0).

redundant type arguments

warning

warning

可隐藏泛型type

For example if you have a call to parametrized method like:

    this.<String>addItem("");

- the usage of <String> will be highlighted.

redundant type cast

warning

warning

多余的类型转换

unnecessary break statement

warning

warning

多余的break操作

Reports on any unnecessary break statements. An break statement is unnecessary when no other statements will be executed when it is removed.

unnecessary continue statement

warning

warning

多余的continue

Reports on any unnecessary continue statements at the end of loops. These may be safely removed.

unnecessary default for enum switch statement

 

warning

enum case就这么多无需default

unnecessary return statement

warning

warning

返回值不使用则void

unnecessary label on break statement

warning

warning

多余的label

unnecessary label on continue statement

warning

warning

多余的label


作者:疯狂阿贾克斯,发布于:2018/08/30
原文:https://www.cnblogs.com/caizhiqin/p/9366036.html