Features

New “Magic Constant” Inspection

Have you ever cursed an API which uses magic integer constants instead of the proper enumeration?

What should I pass as the titleJustification parameter here? 0 or 1?
Can I pass “42” for the titlePosition parameter? Even Javadoc won’t know.
Actually, you must use one of the constants in the TitledBorder class to make the code correct:

I call these constants “magic” because sometimes it is far from easy to figure them out.

Here comes a new “Magic constant” inspection that looks for usages of methods/variables which expect “magic constants” as their arguments:

Then it helps you to replace plain numbers or strings with a proper magic constant:


How does it know if the method expects a “magic constant” argument?

It seems that a number of JDK Swing methods is annotated with a special form of the @beaninfo javadoc tag, which provides the information about allowed values:

Unfortunately, only a handful of the JDK methods are annotated this way. The majority of the rest method parameters are left in the dark.
So we’ve created our own @MagicConstant annotation and annotated some JDK methods and our own code:

As you can see, you just enumerate constant names which can be used in this place.
IntelliJ IDEA then checks arguments of method calls, variable assignments, etc. and warns if expressions involved are not valid, considering the data flow.

@MagicConstant annotation can do the following:

@MagicConstant(intValues = {Const1, Const2,...}) or
@MagicConstant(stringValues = {Const1, Const2,...})

Tells IntelliJ IDEA that only one of the listed constants can be used as an argument.

@MagicConstant(valuesFromClass = ClassName.class)

Tells IntelliJ IDEA that allowed value for the argument is one of the public static final fields declared in the class “ClassName”.

@MagicConstant(flags = {Const1, Const2,...})
Tells IntelliJ IDEA that one or several of the listed integer constants can be combined with the bitwise OR operator.

You can also apply @MagicConstant to another annotation class to create an alias you can use everywhere:

How to make it work in my setup?

1. @MagicConstant annotation sits in the IDEA_HOME/lib/annotations.jar. You have to attach it to your project in Project Structure|Global Libraries dialog.
2. External annotations for the JDK methods sit in the IDEA_HOME/lib/jdkAnnotations.jar. It is attached automatically to your JDK as soon as you enable the “Magic Constant” inspection (see the Project Structure | SDKs | Annotations tab).

image description