简体   繁体   中英

Intellij static final collection inspection

I looked for a IntelliJ inspection, but couldn't find it.

If you take the code snippet below, it is supposed to be a constant, but it is not immutable.

private static final Set<MyEventType> TYPES = EnumSet.of(MyEventType.APPROVED,MyEventType.REJECTED); 

it is perfectly valid to do the following.

TYPES.add(MyEventType.CANCELED);

So is there a IntelliJ inspection which would give mi a warning that my collection is not immutable. Usually it is what you want with static final fields.

This would be the correct code:

private static final Set<MyEventType> TYPES =  Collections.unmodifiableSet(EnumSet.of(MyEventType.APPROVED,MyEventType.REJECTED)); 

The relevant inspection is Settings > Editor > Inspections > Java > Naming conventions > Non-constant field with uppercase name.

That's really all that's wrong with the above. It just happens that you intended the set to be unmodifiable, but EnumSet.of is fully documented to return a modifiable set. The convention for "constants" is that the field itself is constant, not the referenced object (compare, for example, the use of LOGGER as a field name: the logger reference is constant, but the logger instance can be modified). Intellij IDEA doesn't (as far as I know; I may be corrected) have an inspection for using uppercase field names for modifiable objects.

IntelliJ can already identify cases of calling add on an immutable collection:

private final Set<SessionServerState> ALL_STATES = Collections.unmodifiableSet(EnumSet.allOf(SessionServerState.class));

ALL_STATES.add(...);

在此处输入图片说明

If you expand this tooltip, it comes from the Constant conditions & exceptions inspection.

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM