protected void assertValue( Reflection reflection, Object target, Property property, Object expectedValue) throws Exception { Object actual = reflection.getProperty(target, property); assertThat(actual, is(expectedValue)); assertThat(reflection.getPropertyAsString(target, property), is(notNullValue())); }
private void tstReflectionDelegation() throws ClassNotFoundException { Reflection test = new Reflection( new GenericReflector( null, new JdkReflector(Thread.currentThread().getContextClassLoader()))); test.tstEverything(); }
private void send(CommandSender sender, String jsonString) { if (!(sender instanceof Player)) { sender.sendMessage(toOldMessageFormat()); return; } Player player = (Player) sender; try { Object handle = Reflection.getHandle(player); Object connection = Reflection.getField(handle.getClass(), "playerConnection").get(handle); Reflection.getMethod(connection.getClass(), "sendPacket", Reflection.getNMSClass("Packet")) .invoke(connection, createChatPacket(jsonString)); } catch (IllegalArgumentException e) { Bukkit.getLogger().log(Level.WARNING, "Argument could not be passed.", e); } catch (IllegalAccessException e) { Bukkit.getLogger().log(Level.WARNING, "Could not access method.", e); } catch (InstantiationException e) { Bukkit.getLogger().log(Level.WARNING, "Underlying class is abstract.", e); } catch (InvocationTargetException e) { Bukkit.getLogger().log(Level.WARNING, "A error has occured durring invoking of method.", e); } catch (NoSuchMethodException e) { Bukkit.getLogger().log(Level.WARNING, "Could not find method.", e); } catch (ClassNotFoundException e) { Bukkit.getLogger().log(Level.WARNING, "Could not find class.", e); } }
private Object createChatPacket(String json) throws IllegalArgumentException, IllegalAccessException, InstantiationException, InvocationTargetException { if (nmsChatSerializerGsonInstance == null) { // Find the field and its value, completely bypassing obfuscation for (Field declaredField : Reflection.getNMSClass("ChatSerializer").getDeclaredFields()) { if (Modifier.isFinal(declaredField.getModifiers()) && Modifier.isStatic(declaredField.getModifiers()) && declaredField.getType() == com.google.gson.Gson.class) { // We've found our field declaredField.setAccessible(true); nmsChatSerializerGsonInstance = (com.google.gson.Gson) declaredField.get(null); break; } } } // Since the method is so simple, and all the obfuscated methods have the same name, it's easier // to reimplement 'IChatBaseComponent a(String)' than to reflectively call it // Of course, the implementation may change, but fuzzy matches might break with signature // changes Object serializedChatComponent = nmsChatSerializerGsonInstance.fromJson(json, Reflection.getNMSClass("IChatBaseComponent")); return nmsPacketPlayOutChatConstructor.newInstance(serializedChatComponent); }
/** * Set the behavior of the current editing component to display information about a statistic * parameter with an entity type when the client hovers over the text. * * <p>Tooltips do not inherit display characteristics, such as color and styles, from the message * component on which they are applied. * * @param which The statistic to display. * @param entity The sole entity type parameter to the statistic. * @return This builder instance. * @exception IllegalArgumentException If the statistic requires a parameter which was not * supplied, or was supplied a parameter that was not required. */ public FancyMessage statisticTooltip(final Statistic which, EntityType entity) { Type type = which.getType(); if (type == Type.UNTYPED) { throw new IllegalArgumentException("That statistic needs no additional parameter!"); } if (type != Type.ENTITY) { throw new IllegalArgumentException( "Wrong parameter type for that statistic - needs " + type + "!"); } try { Object statistic = Reflection.getMethod( Reflection.getOBCClass("CraftStatistic"), "getEntityStatistic", Statistic.class, EntityType.class) .invoke(null, which, entity); return achievementTooltip( (String) Reflection.getField(Reflection.getNMSClass("Statistic"), "name").get(statistic)); } catch (IllegalAccessException e) { Bukkit.getLogger().log(Level.WARNING, "Could not access method.", e); return this; } catch (IllegalArgumentException e) { Bukkit.getLogger().log(Level.WARNING, "Argument could not be passed.", e); return this; } catch (InvocationTargetException e) { Bukkit.getLogger().log(Level.WARNING, "A error has occured durring invoking of method.", e); return this; } }
/** * Sends this message to a player. The player will receive the fully-fledged formatted display of * this message. * * @param player The player who will receive the message. */ public void send(Player player) { try { Object handle = Reflection.getHandle(player); Object connection = Reflection.getField(handle.getClass(), "playerConnection").get(handle); Reflection.getMethod(connection.getClass(), "sendPacket", Reflection.getNMSClass("Packet")) .invoke(connection, createChatPacket(Message.Colorize(toJSONString()))); } catch (Exception e) { e.printStackTrace(); } }
@Test public void shouldFindMethodsWithNameMatchingRegularExpression() { Method[] stringMethods = stringReflection.findMethods("indexO.", true); assertThat(stringMethods.length, is(4)); for (Method method : stringMethods) { assertThat(method.getName(), is("indexOf")); } stringMethods = stringReflection.findMethods(".+gth", true); assertThat(stringMethods.length, is(1)); for (Method method : stringMethods) { assertThat(method.getName(), is("length")); } }
/** * Set the behavior of the current editing component to display information about an achievement * when the client hovers over the text. * * <p>Tooltips do not inherit display characteristics, such as color and styles, from the message * component on which they are applied. * * @param which The achievement to display. * @return This builder instance. */ public FancyMessage achievementTooltip(final Achievement which) { try { Object achievement = Reflection.getMethod( Reflection.getOBCClass("CraftStatistic"), "getNMSAchievement", Achievement.class) .invoke(null, which); return achievementTooltip( (String) Reflection.getField(Reflection.getNMSClass("Achievement"), "name").get(achievement)); } catch (Exception e) { e.printStackTrace(); return this; } }
@Test public void shouldGetClassNameWith8DPrimitiveArray() { assertThat( Reflection.getClassName(new int[0][0][0][0][0][0][0][0].getClass()), is("int[][][][][][][][]")); assertThat( Reflection.getClassName(new boolean[0][0][0][0][0][0][0][0].getClass()), is("boolean[][][][][][][][]")); assertThat( Reflection.getClassName(new long[0][0][0][0][0][0][0][0].getClass()), is("long[][][][][][][][]")); assertThat( Reflection.getClassName(new short[0][0][0][0][0][0][0][0].getClass()), is("short[][][][][][][][]")); assertThat( Reflection.getClassName(new float[0][0][0][0][0][0][0][0].getClass()), is("float[][][][][][][][]")); assertThat( Reflection.getClassName(new double[0][0][0][0][0][0][0][0].getClass()), is("double[][][][][][][][]")); assertThat( Reflection.getClassName(new char[0][0][0][0][0][0][0][0].getClass()), is("char[][][][][][][][]")); assertThat( Reflection.getClassName(new byte[0][0][0][0][0][0][0][0].getClass()), is("byte[][][][][][][][]")); }
@Test public void shouldGetClassNameWithPrimitive() { assertThat(Reflection.getClassName(Integer.TYPE), is("int")); assertThat(Reflection.getClassName(Boolean.TYPE), is("boolean")); assertThat(Reflection.getClassName(Long.TYPE), is("long")); assertThat(Reflection.getClassName(Short.TYPE), is("short")); assertThat(Reflection.getClassName(Float.TYPE), is("float")); assertThat(Reflection.getClassName(Double.TYPE), is("double")); assertThat(Reflection.getClassName(Character.TYPE), is("char")); assertThat(Reflection.getClassName(Byte.TYPE), is("byte")); assertThat(Reflection.getClassName(Void.TYPE), is("void")); }
@Test public void requiredFields() throws Exception { Collection<Method> methods = Reflection.requiredFields(VariousMethods.class); assertEquals(1, methods.size()); assertTrue(methods.contains(VariousMethods.class.getMethod("num"))); }
private Object createChatPacket(String json) throws IllegalArgumentException, IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchMethodException, ClassNotFoundException { if (nmsChatSerializerGsonInstance == null) { // Find the field and its value, completely bypassing obfuscation Class<?> chatSerializerClazz; String version = Reflection.getVersion(); double majorVersion = Double.parseDouble(version.replace('_', '.').substring(1, 4)); int lesserVersion = Integer.parseInt(version.substring(6, 7)); if (majorVersion < 1.8 || (majorVersion == 1.8 && lesserVersion == 1)) { chatSerializerClazz = Reflection.getNMSClass("ChatSerializer"); } else { chatSerializerClazz = Reflection.getNMSClass("IChatBaseComponent$ChatSerializer"); } if (chatSerializerClazz == null) { throw new ClassNotFoundException("Can't find the ChatSerializer class"); } for (Field declaredField : chatSerializerClazz.getDeclaredFields()) { if (Modifier.isFinal(declaredField.getModifiers()) && Modifier.isStatic(declaredField.getModifiers()) && declaredField.getType().getName().endsWith("Gson")) { // We've found our field declaredField.setAccessible(true); nmsChatSerializerGsonInstance = declaredField.get(null); fromJsonMethod = nmsChatSerializerGsonInstance .getClass() .getMethod("fromJson", String.class, Class.class); break; } } } // Since the method is so simple, and all the obfuscated methods have the same name, it's easier // to reimplement 'IChatBaseComponent a(String)' than to reflectively call it // Of course, the implementation may change, but fuzzy matches might break with signature // changes Object serializedChatComponent = fromJsonMethod.invoke( nmsChatSerializerGsonInstance, json, Reflection.getNMSClass("IChatBaseComponent")); return nmsPacketPlayOutChatConstructor.newInstance(serializedChatComponent); }
public FancyMessage(final TextualComponent firstPartText) { messageParts = new ArrayList<MessagePart>(); messageParts.add(new MessagePart(firstPartText)); jsonString = null; dirty = false; if (nmsPacketPlayOutChatConstructor == null) { try { nmsPacketPlayOutChatConstructor = Reflection.getNMSClass("PacketPlayOutChat") .getDeclaredConstructor(Reflection.getNMSClass("IChatBaseComponent")); nmsPacketPlayOutChatConstructor.setAccessible(true); } catch (Exception e) { e.printStackTrace(); } } }
@Test public void fieldGetters() throws Exception { Collection<Method> methods = Reflection.fieldGetters(VariousMethods.class); assertEquals(2, methods.size()); assertTrue(methods.contains(VariousMethods.class.getMethod("num"))); assertTrue(methods.contains(VariousMethods.class.getMethod("customKey"))); }
/** * Set the behavior of the current editing component to display information about a parameterless * statistic when the client hovers over the text. * * <p>Tooltips do not inherit display characteristics, such as color and styles, from the message * component on which they are applied. * * @param which The statistic to display. * @return This builder instance. * @exception IllegalArgumentException If the statistic requires a parameter which was not * supplied. */ public FancyMessage statisticTooltip(final Statistic which) { Type type = which.getType(); if (type != Type.UNTYPED) { throw new IllegalArgumentException( "That statistic requires an additional " + type + " parameter!"); } try { Object statistic = Reflection.getMethod( Reflection.getOBCClass("CraftStatistic"), "getNMSStatistic", Statistic.class) .invoke(null, which); return achievementTooltip( (String) Reflection.getField(Reflection.getNMSClass("Statistic"), "name").get(statistic)); } catch (Exception e) { e.printStackTrace(); return this; } }
private static <D extends GenericDeclaration> TypeVariable<D> newTypeVariableImpl( D genericDeclaration, String name, Type[] bounds) { TypeVariableImpl<D> typeVariableImpl = new TypeVariableImpl<D>(genericDeclaration, name, bounds); @SuppressWarnings("unchecked") TypeVariable<D> typeVariable = Reflection.newProxy( TypeVariable.class, new TypeVariableInvocationHandler(typeVariableImpl)); return typeVariable; }
public FancyMessage(final TextualComponent firstPartText) { messageParts = new ArrayList<MessagePart>(); messageParts.add(new MessagePart(firstPartText)); jsonString = null; dirty = false; if (nmsPacketPlayOutChatConstructor == null) { try { nmsPacketPlayOutChatConstructor = Reflection.getNMSClass("PacketPlayOutChat") .getDeclaredConstructor(Reflection.getNMSClass("IChatBaseComponent")); nmsPacketPlayOutChatConstructor.setAccessible(true); } catch (NoSuchMethodException e) { Bukkit.getLogger().log(Level.SEVERE, "Could not find Minecraft method or constructor.", e); } catch (SecurityException e) { Bukkit.getLogger().log(Level.WARNING, "Could not access constructor.", e); } } }
/** * Set the behavior of the current editing component to display information about an achievement * when the client hovers over the text. * * <p>Tooltips do not inherit display characteristics, such as color and styles, from the message * component on which they are applied. * * @param which The achievement to display. * @return This builder instance. */ public FancyMessage achievementTooltip(final Achievement which) { try { Object achievement = Reflection.getMethod( Reflection.getOBCClass("CraftStatistic"), "getNMSAchievement", Achievement.class) .invoke(null, which); return achievementTooltip( (String) Reflection.getField(Reflection.getNMSClass("Achievement"), "name").get(achievement)); } catch (IllegalAccessException e) { Bukkit.getLogger().log(Level.WARNING, "Could not access method.", e); return this; } catch (IllegalArgumentException e) { Bukkit.getLogger().log(Level.WARNING, "Argument could not be passed.", e); return this; } catch (InvocationTargetException e) { Bukkit.getLogger().log(Level.WARNING, "A error has occured durring invoking of method.", e); return this; } }
public static Object toArrayGuessType(Collection<?> value) { Class<?> componentType = Reflection.getComponentType(value); Object array = Array.newInstance(componentType, value.size()); @SuppressWarnings("unchecked") Iterator<Object> iterator = (Iterator<Object>) value.iterator(); int index = 0; while (iterator.hasNext()) { BeanUtils.idx(array, index, iterator.next()); index++; } return array; }
@Test public void shouldUseAnnotationsOnClassFieldsForProperties() throws Exception { SomeStructure structure = new SomeStructure(); structure.setCount(33); structure.setIdentifier("This is the identifier value"); Reflection reflection = new Reflection(SomeStructure.class); List<Property> props = reflection.getAllPropertiesOn(structure); Map<String, Property> propsByName = reflection.getAllPropertiesByNameOn(structure); assertThat(props.size(), is(3)); assertThat(propsByName.size(), is(3)); Property property = propsByName.remove("identifier"); assertThat(property.getName(), is("identifier")); assertThat(property.getLabel(), is(CommonI18n.noMoreContent.text())); assertThat(property.getDescription(), is(CommonI18n.nullActivityMonitorTaskName.text())); assertThat(property.getCategory(), is(CommonI18n.noMoreContent.text())); assertThat(property.getType().equals(String.class), is(true)); assertThat(property.isReadOnly(), is(false)); assertThat(property, is(findProperty(property.getName(), props))); assertValue(reflection, structure, property, structure.getIdentifier()); property = propsByName.remove("count"); assertThat(property.getName(), is("count")); assertThat(property.getLabel(), is("Count")); assertThat(property.getDescription(), is("This is the count")); assertThat(property.getCategory(), is("")); assertThat(property.getType().equals(Integer.TYPE), is(true)); assertThat(property.isReadOnly(), is(false)); assertValue(reflection, structure, property, structure.getCount()); property = propsByName.remove("onFire"); assertThat(property.getName(), is("onFire")); assertThat(property.getLabel(), is("On Fire")); assertThat(property.getDescription(), is("")); assertThat(property.getCategory(), is("")); assertThat(property.getType().equals(Boolean.TYPE), is(true)); assertThat(property.isReadOnly(), is(true)); assertValue(reflection, structure, property, structure.isOnFire()); }
/** * Set the behavior of the current editing component to display information about a statistic * parametered with an entity type when the client hovers over the text. * * <p>Tooltips do not inherit display characteristics, such as color and styles, from the message * component on which they are applied. * * @param which The statistic to display. * @param entity The sole entity type parameter to the statistic. * @return This builder instance. * @exception IllegalArgumentException If the statistic requires a parameter which was not * supplied, or was supplied a parameter that was not required. */ public FancyMessage statisticTooltip(final Statistic which, EntityType entity) { Type type = which.getType(); if (type == Type.UNTYPED) { throw new IllegalArgumentException("That statistic needs no additional parameter!"); } if (type != Type.ENTITY) { throw new IllegalArgumentException( "Wrong parameter type for that statistic - needs " + type + "!"); } try { Object statistic = Reflection.getMethod( Reflection.getOBCClass("CraftStatistic"), "getEntityStatistic", Statistic.class, EntityType.class) .invoke(null, which, entity); return achievementTooltip( (String) Reflection.getField(Reflection.getNMSClass("Statistic"), "name").get(statistic)); } catch (Exception e) { e.printStackTrace(); return this; } }
@Override public E get(int location) { E result = Reflection.instantiate(clazz); if (useCache) { result = cache.get(location); } else { cursor.moveToPosition(location); result.fromCursor(cursor); cache.put(location, result); if (cache.size() == count) { useCache = true; cursor.close(); } } return result; }
/** * Set the behavior of the current editing component to display information about an item when the * client hovers over the text. * * <p>Tooltips do not inherit display characteristics, such as color and styles, from the message * component on which they are applied. * * @param itemStack The stack for which to display information. * @return This builder instance. */ public FancyMessage itemTooltip(final ItemStack itemStack) { try { Object nmsItem = Reflection.getMethod( Reflection.getOBCClass("inventory.CraftItemStack"), "asNMSCopy", ItemStack.class) .invoke(null, itemStack); return itemTooltip( Reflection.getMethod( Reflection.getNMSClass("ItemStack"), "save", Reflection.getNMSClass("NBTTagCompound")) .invoke(nmsItem, Reflection.getNMSClass("NBTTagCompound").newInstance()) .toString()); } catch (Exception e) { e.printStackTrace(); return this; } }
@Test public void shouldGetClassNameOfInterface() { assertThat(Reflection.getClassName(CharSequence.class), is(CharSequence.class.getName())); assertThat(Reflection.getClassName(List.class), is(List.class.getName())); }
public KFunction compute() { if (reflected == null) { reflected = Reflection.function(this); } return reflected; }
@Test public void shouldNotFindMethodsWhenThereAreNoMethodsWithThatName() { assertThat(stringReflection.findMethods("size", true).length, is(0)); assertThat(stringListReflection.findMethods("argleBargle", true).length, is(0)); }
@Override protected KCallable computeReflected() { return Reflection.mutableProperty1(this); }
@Test public void shouldGetAllPropertiesOnJavaBean() throws Exception { Status status = Status.INFO; int code = 121; I18n msg = CommonI18n.argumentMayNotBeEmpty; Object[] params = new Object[] {"argName"}; String resource = "The source"; String location = "The place to be"; Throwable throwable = null; Problem problem = new Problem(status, code, msg, params, resource, location, throwable); Reflection reflection = new Reflection(Problem.class); List<Property> props = reflection.getAllPropertiesOn(problem); Map<String, Property> propsByName = reflection.getAllPropertiesByNameOn(problem); assertThat(props.size(), is(8)); assertThat(propsByName.size(), is(8)); assertThat(props.containsAll(propsByName.values()), is(true)); Property property = propsByName.remove("status"); assertThat(property.getName(), is("status")); assertThat(property.getLabel(), is("Status")); assertThat(property.getType().equals(Status.class), is(true)); assertThat(property.isReadOnly(), is(true)); assertThat(property, is(findProperty(property.getName(), props))); assertValue(reflection, problem, property, status); property = propsByName.remove("code"); assertThat(property.getName(), is("code")); assertThat(property.getLabel(), is("Code")); assertThat(property.getType().equals(Integer.TYPE), is(true)); assertThat(property.isReadOnly(), is(true)); assertValue(reflection, problem, property, code); property = propsByName.remove("message"); assertThat(property.getName(), is("message")); assertThat(property.getLabel(), is("Message")); assertThat(property.getType().equals(I18n.class), is(true)); assertThat(property.isReadOnly(), is(true)); assertValue(reflection, problem, property, msg); property = propsByName.remove("messageString"); assertThat(property.getName(), is("messageString")); assertThat(property.getLabel(), is("Message String")); assertThat(property.getType().equals(String.class), is(true)); assertThat(property.isReadOnly(), is(true)); assertValue(reflection, problem, property, msg.text(params)); property = propsByName.remove("parameters"); assertThat(property.getName(), is("parameters")); assertThat(property.getLabel(), is("Parameters")); assertThat(property.getType().equals(Object[].class), is(true)); assertThat(property.isReadOnly(), is(true)); assertValue(reflection, problem, property, params); property = propsByName.remove("resource"); assertThat(property.getName(), is("resource")); assertThat(property.getLabel(), is("Resource")); assertThat(property.getType().equals(String.class), is(true)); assertThat(property.isReadOnly(), is(true)); assertValue(reflection, problem, property, resource); property = propsByName.remove("location"); assertThat(property.getName(), is("location")); assertThat(property.getLabel(), is("Location")); assertThat(property.getType().equals(String.class), is(true)); assertThat(property.isReadOnly(), is(true)); assertValue(reflection, problem, property, location); property = propsByName.remove("throwable"); assertThat(property.getName(), is("throwable")); assertThat(property.getLabel(), is("Throwable")); assertThat(property.getType().equals(Throwable.class), is(true)); assertThat(property.isReadOnly(), is(true)); assertValue(reflection, problem, property, throwable); assertThat(propsByName.isEmpty(), is(true)); }
@Test public void shouldHaveTargetClass() { assertThat(stringReflection.getTargetClass() == String.class, is(true)); assertThat(stringListReflection.getTargetClass() == List.class, is(true)); }
@Test public void shouldGetClassNameForClass() { assertThat(Reflection.getClassName(String.class), is(String.class.getName())); assertThat(Reflection.getClassName(ArrayList.class), is(ArrayList.class.getName())); assertThat(Reflection.getClassName(StringUtil.class), is(StringUtil.class.getName())); }