Search code examples
pluginsspigot

Casting warning


private void loadGlobalChest() {
        ConfigurationSection inventorySection = items.getConfigurationSection("inventory");
        if (inventorySection != null) {
            globalChestInventory.setContents(((List<ItemStack>) inventorySection.getList("items")).toArray(ItemStack[]::new));
        }
    }

Can anyone tell me why when I try to cast List it gives me a warning? (which is Type safety: Unchecked cast from List<capture#1-of ?> to List)

It throws an error in the console, telling me that could not pass the InventoryOpenEvent because the return value of ConfigurationSection.getList(String) is null.

I think that probably the error is in the file where I store the items of the chest, because when there are no items, all the lines are null.

EDIT: https://pastebin.com/TxhY91HU


Solution

  • The warning is there because you are trying to cast a List<ItemStack> to a List<Object>. This is not a safe way to do it because the List<Object> could be any Object and you can't just cast a random object to an ItemStack. To make sure the objects you are getting from the config file are ItemStacks you need to check that each object in the List<Object> returned from inventorySection.getList("items") is an instance of ItemStack.

    private void loadGlobalChest() {
            ConfigurationSection inventorySection = items.getConfigurationSection("inventory");
            if (inventorySection != null) {
                // Create a list of items
                List<ItemStack> itemList = new ArrayList<ItemStack>();
                //Loop though the list of objects in the config
                for (Object obj : inventorySection.getList("items")) {
                    if (obj instanceof ItemStack) {
                        // If the object is an ItemStack, add it to the list of items
                        itemList.add((ItemStack)obj);
                    }
                }
                globalChestInventory.setContents(itemList.toArray(ItemStack[]::new));
            }
        }
    

    As for the null error, it is self-explanatory, It tells you the return value of ConfigurationSection.getList(String) is null. In the spigot config ConfigurationSection.getList(String) returns null "If the String does not exist and no default value was specified". The config section you are trying to get doesn't exist. You need to add a null check for the config section before using it and you need to make sure the list is saved in the config.