Solved CraftBlockData cannot be cast to Ageable

Discussion in 'Plugin Development' started by Script1996, Sep 27, 2021.

  1. Offline

    Script1996

    Hi everyone,

    I have this code:
    Code:
    public void onClick(PlayerInteractEvent e) {
            if (e.getAction() == Action.LEFT_CLICK_BLOCK
                    && (e.getClickedBlock().getType() == Material.WHEAT || e.getClickedBlock().getType() == Material.CARROTS
                            || e.getClickedBlock().getType() == Material.POTATOES)) {
                if (e.getPlayer().getInventory().getItemInMainHand().getType().equals(Material.WOODEN_HOE)) {
                    e.setCancelled(true);
                    int radius = 2;
                    Block middle = e.getClickedBlock();
                    Ageable ab = (Ageable) middle.getBlockData();
                    if (ab.getAge() == ab.getMaximumAge()) {
                        middle.breakNaturally();
                        for (int x = radius; x >= -radius; x--) {
                            for (int y = radius; y >= -radius; y--) {
                                for (int z = radius; z >= -radius; z--) {
                                    BlockData bd = middle.getRelative(x,0, z).getBlockData();
                                    Ageable abR = (Ageable) bd;
                                }
                            }
                        }
                    }
                }
            }
        }
    The funny thing is, "Ageable ab" works, while "Ageable abR" throws the Error "java.lang.ClassCastException: class org.bukkit.craftbukkit.v1_17_R1.block.data.CraftBlockData cannot be cast to class org.bukkit.block.data.Ageable"

    Do you have any idea why the code suddenly doesn't accept the same thing as before ?
     
  2. Online

    Kars

    Probably because the second block is not an ageable block.
    I could be wrong.
     
    Script1996 likes this.
  3. Offline

    davidclue

    @Script1996 That is weird idk why that's happening but first off don't go about casting stuff without checking it and second off just simply don't cast it to an object then, only cast it to use its methods.
     
    Script1996 likes this.
  4. Offline

    Script1996

    You're both right..
    I debugged it while sending me the blocks. "AIR" is not an ageable block :D

    Thank you both, I got it working now :)
     

Share This Page