Skip to content

BlockPlaceEvent is using a null for inhand item

We received a bug report from SlimeDog who was seeing console errors. After some investigation, it looks like IronDoors is the source due to a call to BlockPlaceEvent with a null ItemStack.

Here is the line: https://gitlab.com/RandomUnknown/irondoors/-/blob/master/src/main/java/com/rngservers/irondoors/events/Events.java#L38

BlockPlaceEvent placeEvent = new BlockPlaceEvent(event.getClickedBlock(), event.getClickedBlock().getState(), event.getClickedBlock(), event.getItem(), event.getPlayer(), true, EquipmentSlot.HAND);

In this code, the bug is caused by constructing BlockPlaceEvent with the 4th parameter (ItemStack itemInHand) being event.getItem() and it being null. According to the BlockPlaceEvent JavaDocs, this shouldn't be null:

BlockPlaceEvent
public BlockPlaceEvent​(@NotNull
                       @NotNull Block placedBlock,
                       @NotNull
                       @NotNull BlockState replacedBlockState,
                       @NotNull
                       @NotNull Block placedAgainst,
                       @NotNull
                       @NotNull ItemStack itemInHand,
                       @NotNull
                       @NotNull Player thePlayer,
                       boolean canBuild,
                       @NotNull
                       @NotNull EquipmentSlot hand)

However, as PlayerInteractEvent getItem() can return a null, so feeding in getItem directly to BlockPlaceEvent is what is causing the issue:

getItem
@Nullable
public @Nullable ItemStack getItem​()
Returns the item in hand represented by this event
Returns:
ItemStack the item used

What I suggest is that if getItem() returns null, you instead feed a new ItemStack(Material.AIR) to the new BlockPlaceEvent because that will meet the NonNull contract.

On our side, we've put in a null check, but it's best if the fix goes in your code so that other plugins won't hit the same issue.