package de.spline.kvm.utils; import java.awt.PopupMenu; import java.lang.reflect.Field; import nn.pp.rc.RemoteConsoleApplet; import nn.pp.rc.ServerConsolePanelBase; public class ReflectionUtils { /** * Set a field of an object with reflection. This ignores all access * permissions (f.e. private) and accesses the field by name (so it works * for strange field names). * * @param cls * @param instance * @param field * @param value */ public static void setField(Class cls, Object instance, String field, Object value) { try { Field f = cls.getDeclaredField(field); f.setAccessible(true); f.set(instance, value); } catch (NoSuchFieldException | IllegalAccessException e) { e.printStackTrace(); } } /** * Get a field of an object with reflection. This ignores all access * permissions (f.e. private) and accesses the field by name (so it works * for strange field names). * * @param cls * @param instance * @param field * @return */ public static Object getField(Class cls, Object instance, String field) { try { Field f = cls.getDeclaredField(field); f.setAccessible(true); return f.get(instance); } catch (NoSuchFieldException | IllegalAccessException e) { e.printStackTrace(); } return null; } /** * Get the ServerConsolePanelBase field from the applet instance. We need * to use reflection here, because the obfuscation has produced strange * field names and we cannot access it using normal methods. * * @param applet RemoteConsoleApplet instance * @return ServerConsolePanelBase instance of this applet */ public static ServerConsolePanelBase getConsolePanel(RemoteConsoleApplet applet) { return (ServerConsolePanelBase) ReflectionUtils.getField(RemoteConsoleApplet.class, applet, "else"); } /** * Get the popup option menu from a ServerConsolePanelBase instance. The * field name is okay-ish here, but we also need to use reflection here * because this field in private. * * (We use this option menu to fix a silly bug: The menu is not displayed, * because the "label" is removed after initialization and this is causing * NullPointerExceptions.) * * @param consolePanel ServerConsolePanelBase instance * @return options menu */ public static PopupMenu getOptionMenu(ServerConsolePanelBase consolePanel) { return (PopupMenu)ReflectionUtils.getField(ServerConsolePanelBase.class, consolePanel, "G"); } }