Skip to content

Instantly share code, notes, and snippets.

@Yuhtin
Created April 18, 2021 14:13
Show Gist options
  • Save Yuhtin/aeb871b91625a54a36cb4101c6e0a287 to your computer and use it in GitHub Desktop.
Save Yuhtin/aeb871b91625a54a36cb4101c6e0a287 to your computer and use it in GitHub Desktop.
TextComponent with item (Reflection)
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import net.md_5.bungee.api.chat.BaseComponent;
import net.md_5.bungee.api.chat.HoverEvent;
import net.md_5.bungee.api.chat.TextComponent;
import org.bukkit.Bukkit;
import org.bukkit.inventory.ItemStack;
import java.lang.reflect.Method;
import java.util.logging.Level;
public final class TextUtils {
public static TextComponent sendItemTooltipMessage(final String message, final ItemStack item) {
final String itemJson = convertItemStackToJson(item);
final BaseComponent[] hoverEventComponents = {new TextComponent(itemJson)};
final HoverEvent event = new HoverEvent(HoverEvent.Action.SHOW_ITEM, hoverEventComponents);
final TextComponent component = new TextComponent(message);
component.setHoverEvent(event);
return component;
}
private static String convertItemStackToJson(final ItemStack itemStack) {
final Class<?> craftItemStackClazz = ReflectionUtils.getOBCClass("inventory.CraftItemStack");
final Method asNMSCopyMethod = ReflectionUtils.getMethod(craftItemStackClazz, "asNMSCopy", ItemStack.class);
final Class<?> nmsItemStackClazz = ReflectionUtils.getNMSClass("ItemStack");
final Class<?> nbtTagCompoundClazz = ReflectionUtils.getNMSClass("NBTTagCompound");
final Method saveNmsItemStackMethod = ReflectionUtils.getMethod(nmsItemStackClazz, "save", nbtTagCompoundClazz);
Object itemAsJsonObject;
try {
final Object nmsNbtTagCompoundObj = nbtTagCompoundClazz.newInstance();
final Object nmsItemStackObj = asNMSCopyMethod.invoke(null, itemStack);
itemAsJsonObject = saveNmsItemStackMethod.invoke(nmsItemStackObj, nmsNbtTagCompoundObj);
} catch (Throwable t) {
Bukkit.getLogger().log(Level.SEVERE, "failed to serialize itemstack to nms item", t);
return null;
}
return itemAsJsonObject.toString();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment