Solved Get name of item

Discussion in 'Spigot Plugin Development' started by BumseBine, Aug 10, 2018.

  1. Hello, today I wanted to make my programming easier and wanted to create a function to create items in an inventory. I need to get the name of the item to make it colorful. I tried it with item.getDisplayName() and item..getLocalizedName() but both got me an null as the name. How do I get the Item Name?
     
  2. you first retrieve the item's itemmeta and then it's displayname

    ItemStack#getItemMeta#getDisplayName

    If the item doesn't have a displayname it will throw a NPE / return null.

    If you wish to get the item's type simply do ItemStack#getType#name
     
    #2 darklazerog, Aug 10, 2018
    Last edited: Aug 12, 2018
  3. I had to mention that I had the meta. So yes i.getType.name works just fine thank you
     
  4. Hey, so I just want to add on to what darklazerog said, you should check to make sure the item isnt null, and the display name isnt null, this is how I always do it.
    Code (Java):
    if(item == null) {return;}
    if(item.getItemMeta() == null) {return;}
    if(item.getItemMeta().getDisplayName() == null) {return;}
    String ItemName = item.getItemMeta().getDisplayName();
     
     
  5. Also I think that you would have to replace the _ to a blank space
     
  6. There are a few things that need to be noticed:

    • The ItemMeta will never be null, if you attempt to get an item's meta and it doesn't exist, a new one will be made.
    • There's already an available method to check for an item's displayName ( ItemMeta#hasDisplayName -> returns a boolean)
     
  7. Another thing to be noticed (I see this done a lot around), don't call getItemMeta() more than one since a new one would be created (Lack of performance). Store the result in a local variable.
     
  8. There's no noticeable nor really any lack of performance. Storing the ItemMeta object into a local variable will only be useful if you're going to implement changes into it, as far as checking is concerned then it's ok not to store the object. I could be wrong however so let me know if you have any different opinion on this matter.
     
  9. Every time you call ItemStack#getItemMeta it creates a new ItemMeta variables and load all properties of that ItemStack

    Code (Java):
        @Override
        public ItemMeta getItemMeta() {
            return getItemMeta(handle);
        }

        public static ItemMeta getItemMeta(net.minecraft.server.ItemStack item) {
            if (!hasItemMeta(item)) {
                return CraftItemFactory.instance().getItemMeta(getType(item));
            }
            switch (getType(item)) {
                case WRITTEN_BOOK:
                    return new CraftMetaBookSigned(item.getTag());
                case WRITABLE_BOOK:
                    return new CraftMetaBook(item.getTag());
                case CREEPER_HEAD:
                case CREEPER_WALL_HEAD:
                case DRAGON_HEAD:
                case DRAGON_WALL_HEAD:
                case PLAYER_HEAD:
                case PLAYER_WALL_HEAD:
                case SKELETON_SKULL:
                case SKELETON_WALL_SKULL:
                case WITHER_SKELETON_SKULL:
                case WITHER_SKELETON_WALL_SKULL:
                case ZOMBIE_HEAD:
                case ZOMBIE_WALL_HEAD:
                    return new CraftMetaSkull(item.getTag());
                case LEATHER_HELMET:
                case LEATHER_CHESTPLATE:
                case LEATHER_LEGGINGS:
                case LEATHER_BOOTS:
                    return new CraftMetaLeatherArmor(item.getTag());
                case POTION:
                case SPLASH_POTION:
                case LINGERING_POTION:
                case TIPPED_ARROW:
                    return new CraftMetaPotion(item.getTag());
                case FILLED_MAP:
                    return new CraftMetaMap(item.getTag());
                case FIREWORK_ROCKET:
                    return new CraftMetaFirework(item.getTag());
                case FIREWORK_STAR:
                    return new CraftMetaCharge(item.getTag());
                case ENCHANTED_BOOK:
                    return new CraftMetaEnchantedBook(item.getTag());
                case BLACK_BANNER:
                case BLACK_WALL_BANNER:
                case BLUE_BANNER:
                case BLUE_WALL_BANNER:
                case BROWN_BANNER:
                case BROWN_WALL_BANNER:
                case CYAN_BANNER:
                case CYAN_WALL_BANNER:
                case GRAY_BANNER:
                case GRAY_WALL_BANNER:
                case GREEN_BANNER:
                case GREEN_WALL_BANNER:
                case LIGHT_BLUE_BANNER:
                case LIGHT_BLUE_WALL_BANNER:
                case LIGHT_GRAY_BANNER:
                case LIGHT_GRAY_WALL_BANNER:
                case LIME_BANNER:
                case LIME_WALL_BANNER:
                case MAGENTA_BANNER:
                case MAGENTA_WALL_BANNER:
                case ORANGE_BANNER:
                case ORANGE_WALL_BANNER:
                case PINK_BANNER:
                case PINK_WALL_BANNER:
                case PURPLE_BANNER:
                case PURPLE_WALL_BANNER:
                case RED_BANNER:
                case RED_WALL_BANNER:
                case WHITE_BANNER:
                case WHITE_WALL_BANNER:
                case YELLOW_BANNER:
                case YELLOW_WALL_BANNER:
                    return new CraftMetaBanner(item.getTag());
                case BAT_SPAWN_EGG:
                case BLAZE_SPAWN_EGG:
                case CAVE_SPIDER_SPAWN_EGG:
                case CHICKEN_SPAWN_EGG:
                case COW_SPAWN_EGG:
                case CREEPER_SPAWN_EGG:
                case DONKEY_SPAWN_EGG:
                case ELDER_GUARDIAN_SPAWN_EGG:
                case ENDERMAN_SPAWN_EGG:
                case ENDERMITE_SPAWN_EGG:
                case EVOKER_SPAWN_EGG:
                case GHAST_SPAWN_EGG:
                case GUARDIAN_SPAWN_EGG:
                case HORSE_SPAWN_EGG:
                case HUSK_SPAWN_EGG:
                case LLAMA_SPAWN_EGG:
                case MAGMA_CUBE_SPAWN_EGG:
                case MOOSHROOM_SPAWN_EGG:
                case MULE_SPAWN_EGG:
                case OCELOT_SPAWN_EGG:
                case PARROT_SPAWN_EGG:
                case PIG_SPAWN_EGG:
                case POLAR_BEAR_SPAWN_EGG:
                case RABBIT_SPAWN_EGG:
                case SHEEP_SPAWN_EGG:
                case SHULKER_SPAWN_EGG:
                case SILVERFISH_SPAWN_EGG:
                case SKELETON_HORSE_SPAWN_EGG:
                case SKELETON_SPAWN_EGG:
                case SLIME_SPAWN_EGG:
                case SPIDER_SPAWN_EGG:
                case SQUID_SPAWN_EGG:
                case STRAY_SPAWN_EGG:
                case VEX_SPAWN_EGG:
                case VILLAGER_SPAWN_EGG:
                case VINDICATOR_SPAWN_EGG:
                case WITCH_SPAWN_EGG:
                case WITHER_SKELETON_SPAWN_EGG:
                case WOLF_SPAWN_EGG:
                case ZOMBIE_HORSE_SPAWN_EGG:
                case ZOMBIE_PIGMAN_SPAWN_EGG:
                case ZOMBIE_SPAWN_EGG:
                case ZOMBIE_VILLAGER_SPAWN_EGG:
                    return new CraftMetaSpawnEgg(item.getTag());
                case KNOWLEDGE_BOOK:
                    return new CraftMetaKnowledgeBook(item.getTag());
                case FURNACE:
                case CHEST:
                case TRAPPED_CHEST:
                case JUKEBOX:
                case DISPENSER:
                case DROPPER:
                case SIGN:
                case SPAWNER:
                case NOTE_BLOCK:
                case BREWING_STAND:
                case ENCHANTING_TABLE:
                case COMMAND_BLOCK:
                case REPEATING_COMMAND_BLOCK:
                case CHAIN_COMMAND_BLOCK:
                case BEACON:
                case DAYLIGHT_DETECTOR:
                case HOPPER:
                case COMPARATOR:
                case SHIELD:
                case STRUCTURE_BLOCK:
                case SHULKER_BOX:
                case WHITE_SHULKER_BOX:
                case ORANGE_SHULKER_BOX:
                case MAGENTA_SHULKER_BOX:
                case LIGHT_BLUE_SHULKER_BOX:
                case YELLOW_SHULKER_BOX:
                case LIME_SHULKER_BOX:
                case PINK_SHULKER_BOX:
                case GRAY_SHULKER_BOX:
                case LIGHT_GRAY_SHULKER_BOX:
                case CYAN_SHULKER_BOX:
                case PURPLE_SHULKER_BOX:
                case BLUE_SHULKER_BOX:
                case BROWN_SHULKER_BOX:
                case GREEN_SHULKER_BOX:
                case RED_SHULKER_BOX:
                case BLACK_SHULKER_BOX:
                case ENDER_CHEST:
                    return new CraftMetaBlockState(item.getTag(), CraftMagicNumbers.getMaterial(item.getItem()));
                case TROPICAL_FISH_BUCKET:
                    return new CraftMetaTropicalFishBucket(item.getTag());
                default:
                    return new CraftMetaItem(item.getTag());
            }
        }
    (Snippet from craftbukkit). And this happens inside a CraftMetaItem constructors
    Code (Java):

        CraftMetaItem(CraftMetaItem meta) {
            if (meta == null) {
                return;
            }

            this.displayName = meta.displayName;
            this.locName = meta.locName;

            if (meta.hasLore()) {
                this.lore = new ArrayList<String>(meta.lore);
            }

            if (meta.hasEnchants()) {
                this.enchantments = new HashMap<Enchantment, Integer>(meta.enchantments);
            }

            this.repairCost = meta.repairCost;
            this.hideFlag = meta.hideFlag;
            this.unbreakable = meta.unbreakable;
            this.damage = meta.damage;
            this.unhandledTags.putAll(meta.unhandledTags);

            this.internalTag = meta.internalTag;
            if (this.internalTag != null) {
                deserializeInternal(internalTag, meta);
            }
        }

        CraftMetaItem(NBTTagCompound tag) {
            if (tag.hasKey(DISPLAY.NBT)) {
                NBTTagCompound display = tag.getCompound(DISPLAY.NBT);

                if (display.hasKey(NAME.NBT)) {
                    try {
                        displayName = IChatBaseComponent.ChatSerializer.a(display.getString(NAME.NBT));
                    } catch (JsonParseException ex) {
                        // Ignore (stripped like Vanilla)
                    }
                }

                if (display.hasKey(LOCNAME.NBT)) {
                    try {
                        locName = IChatBaseComponent.ChatSerializer.a(display.getString(LOCNAME.NBT));
                    } catch (JsonParseException ex) {
                        // Ignore (stripped like Vanilla)
                    }
                }

                if (display.hasKey(LORE.NBT)) {
                    NBTTagList list = display.getList(LORE.NBT, CraftMagicNumbers.NBT.TAG_STRING);
                    lore = new ArrayList<String>(list.size());

                    for (int index = 0; index < list.size(); index++) {
                        String line = list.getString(index);
                        lore.add(line);
                    }
                }
            }

            this.enchantments = buildEnchantments(tag, ENCHANTMENTS);

            if (tag.hasKey(REPAIR.NBT)) {
                repairCost = tag.getInt(REPAIR.NBT);
            }

            if (tag.hasKey(HIDEFLAGS.NBT)) {
                hideFlag = tag.getInt(HIDEFLAGS.NBT);
            }
            if (tag.hasKey(UNBREAKABLE.NBT)) {
                unbreakable = tag.getBoolean(UNBREAKABLE.NBT);
            }
            if (tag.hasKey(DAMAGE.NBT)) {
                damage = tag.getInt(DAMAGE.NBT);
            }

            if (tag.get(ATTRIBUTES.NBT) instanceof NBTTagList) {
                NBTTagList save = null;
                NBTTagList nbttaglist = tag.getList(ATTRIBUTES.NBT, CraftMagicNumbers.NBT.TAG_COMPOUND);

                for (int i = 0; i < nbttaglist.size(); ++i) {
                    if (!(nbttaglist.get(i) instanceof NBTTagCompound)) {
                        continue;
                    }
                    NBTTagCompound nbttagcompound = (NBTTagCompound) nbttaglist.get(i);

                    if (!nbttagcompound.hasKeyOfType(ATTRIBUTES_UUID_HIGH.NBT, CraftMagicNumbers.NBT.TAG_ANY_NUMBER)) {
                        continue;
                    }
                    if (!nbttagcompound.hasKeyOfType(ATTRIBUTES_UUID_LOW.NBT, CraftMagicNumbers.NBT.TAG_ANY_NUMBER)) {
                        continue;
                    }
                    if (!(nbttagcompound.get(ATTRIBUTES_IDENTIFIER.NBT) instanceof NBTTagString) || !CraftItemFactory.KNOWN_NBT_ATTRIBUTE_NAMES.contains(nbttagcompound.getString(ATTRIBUTES_IDENTIFIER.NBT))) {
                        continue;
                    }
                    if (!(nbttagcompound.get(ATTRIBUTES_NAME.NBT) instanceof NBTTagString) || nbttagcompound.getString(ATTRIBUTES_NAME.NBT).isEmpty()) {
                        continue;
                    }
                    if (!nbttagcompound.hasKeyOfType(ATTRIBUTES_VALUE.NBT, CraftMagicNumbers.NBT.TAG_ANY_NUMBER)) {
                        continue;
                    }
                    if (!nbttagcompound.hasKeyOfType(ATTRIBUTES_TYPE.NBT, CraftMagicNumbers.NBT.TAG_ANY_NUMBER) || nbttagcompound.getInt(ATTRIBUTES_TYPE.NBT) < 0 || nbttagcompound.getInt(ATTRIBUTES_TYPE.NBT) > 2) {
                        continue;
                    }

                    if (save == null) {
                        save = new NBTTagList();
                    }

                    NBTTagCompound entry = new NBTTagCompound();
                    entry.set(ATTRIBUTES_UUID_HIGH.NBT, nbttagcompound.get(ATTRIBUTES_UUID_HIGH.NBT));
                    entry.set(ATTRIBUTES_UUID_LOW.NBT, nbttagcompound.get(ATTRIBUTES_UUID_LOW.NBT));
                    entry.set(ATTRIBUTES_IDENTIFIER.NBT, nbttagcompound.get(ATTRIBUTES_IDENTIFIER.NBT));
                    entry.set(ATTRIBUTES_NAME.NBT, nbttagcompound.get(ATTRIBUTES_NAME.NBT));
                    entry.set(ATTRIBUTES_VALUE.NBT, nbttagcompound.get(ATTRIBUTES_VALUE.NBT));
                    entry.set(ATTRIBUTES_TYPE.NBT, nbttagcompound.get(ATTRIBUTES_TYPE.NBT));
                    save.add(entry);
                }

                unhandledTags.put(ATTRIBUTES.NBT, save);
            }

            Set<String> keys = tag.getKeys();
            for (String key : keys) {
                if (!getHandledTags().contains(key)) {
                    unhandledTags.put(key, tag.get(key));
                }
            }
        }

        static Map<Enchantment, Integer> buildEnchantments(NBTTagCompound tag, ItemMetaKey key) {
            if (!tag.hasKey(key.NBT)) {
                return null;
            }

            NBTTagList ench = tag.getList(key.NBT, CraftMagicNumbers.NBT.TAG_COMPOUND);
            Map<Enchantment, Integer> enchantments = new HashMap<Enchantment, Integer>(ench.size());

            for (int i = 0; i < ench.size(); i++) {
                String id = ((NBTTagCompound) ench.get(i)).getString(ENCHANTMENTS_ID.NBT);
                int level = 0xffff & ((NBTTagCompound) ench.get(i)).getShort(ENCHANTMENTS_LVL.NBT);

                Enchantment enchant = Enchantment.getByKey(CraftNamespacedKey.fromString(id));
                if (enchant != null) {
                    enchantments.put(enchant, level);
                }
            }

            return enchantments;
        }
     
    So, yeah. It's not a big deal, but it's does help quite a bunch when you are calling this method a lot.