Getting DisplayName from a Renamed item

Discussion in 'Spigot Plugin Development' started by x313, Apr 27, 2017.

  1. WAS

    WAS

    You should make sure the item isn't null before accessing any of it's methods. Additionally he wants the displayname and doesn't check if the item has meta to fetch one.

    Code (Java):
    ItemStack clicked = new ItemStack(event.getCurrentItem());
    if ( clicked != null && clicked.getType().equals(Material.WATCH) && clicked.hasItemMeta() ) {
      ItemMeta cmeta = clicked.getItemMeta();
      if ( cmeta.getDisplayName() != null ) {
        String cname = cmeta.getDisplayName();
        //do stuff here
      }
    }
    If we are only interested in this type of item too, might as well just bail out as early as possible.

    Code (Java):
    ItemStack clicked = new ItemStack(event.getCurrentItem());
    // return; or return false; or whatever return type is | return null;
    if ( clicked == null || ! ( clicked.getType().equals(Material.WATCH) ) || ! ( clicked.hasItemMeta() ) )
      return;
    ItemMeta cmeta = clicked.getItemMeta();
    if ( cmeta.getDisplayName() == null )
      return;
    String cname = cmeta.getDisplayName();
    //do stuff here
    Moar stuff: If you are creating a special item, and relying on the displayname to determine if it's special, you'll want to add a Anvil event and make sure they are not creating your special item. If they are, cancel and remove the result.
     
    #21 WAS, Apr 27, 2017
    Last edited: Apr 27, 2017