Created
April 18, 2021 14:13
-
-
Save Yuhtin/aeb871b91625a54a36cb4101c6e0a287 to your computer and use it in GitHub Desktop.
TextComponent with item (Reflection)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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