1.18 Cast to chest error

Discussion in 'Spigot Plugin Development' started by Beancake12, May 14, 2022.

  1. I have trouble casting a block to a chest. I've done this before in another project, excatly like this and it works fine, but I can't solve this one atm.

    Location chestLocation = new Location(world, chestX, chestY, chestZ);
    chestLocation.getBlock().setType(Material.CHEST);
    Chest chest = (Chest) chestLocation.getBlock().getState();

    Error message:
    java.lang.ClassCastException: class org.bukkit.craftbukkit.v1_18_R2.block.CraftBlockState cannot be cast to class org.bukkit.block.Chest (org.bukkit.craftbukkit.v1_18_R2.block.CraftBlockState and org.bukkit.block.Chest are in unnamed module of loader java.net.URLClassLoader @46ee7fe8)


    I've had this working in another plugin, and after updating BuildTools and recompiling the old plugin it stopped working.
     
  2. Fahrenheit451

    Supporter

    It looks like your imports probably aren't correct or conflicting. Check which chest is being imported. The code will certainly work without error with standard org.bukkit.block.Chest and org.bukkit.Location imports.
     
  3. Here are my imports.

    import org.bukkit.block.Block;
    import org.bukkit.block.Chest;
    import org.bukkit.Location;


    After a lot of tampering I discovered that it's working when I move my code outside the constructor. But in the end I ended up storing it as a block then casting it when i needed to use it as a chest.