简体   繁体   中英

Disable “Constant conditions & exceptions” inspection for field in IntelliJ IDEA

I'm using a framework (Minecraft Forge) that injects specific objects into public static final fields with null values (through the @CapabilityInject and @ObjectHolder annotations). Unfortunately whenever I reference one of these fields in a context that doesn't allow null values, the "Constant conditions & exceptions" inspection in IntelliJ IDEA warns me that the field may be null (because it doesn't know about the injection).

I know that these fields won't be null when they're accessed, so I'd like to disable the warning for them.

Is there a way to disable the warning for a specific field or all fields in a class? Adding @SuppressWarnings("ConstantConditions") or //noinspection ConstantConditions to the field doesn't remove the warning on the field access and adding the annotation to the field's class only removes the warning in that class.

I'd like to avoid adding //noinspection ConstantConditions or null -checks to every location I access the fields from.

diesieben07 answered this in my thread on the Minecraft Forge Forums .

The solution/workaround is to create a method that always returns null , annotate it with @Nonnull and @SuppressWarnings("ConstantConditions") and then use that to initialise the field that will be injected into.

For example:

public class Injection {

    @CapabilityInject
    public static final Capability<IItemHandler> CAPABILITY = getNull();

    @Nonnull
    @SuppressWarnings({"ConstantConditions", "SameReturnValue"})
    private static <T> T getNull() {
        return null;
    }

    public void doStuff() {
        // No warning
        Capability<IItemHandler> capability = CAPABILITY;
    }
}

Salamander offered an alternative solution in my thread on WTDWTF .

They suggested moving the initialisation to a static initialiser block instead of initialising the fields inline. This seems less hackish than a method that always returns null , but it also adds a lot of clutter if there are a lot of fields to initialise (which there are in my case).

For example:

public class Injection {

    @CapabilityInject
    public static final Capability<IItemHandler> CAPABILITY;

    static {
        CAPABILITY = null;
    }

    public void doStuff() {
        // No warning
        Capability<IItemHandler> capability = CAPABILITY;
    }
}

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