1 package net.pterodactylus.sone.test;
3 import java.lang.reflect.Constructor;
4 import java.lang.reflect.Field;
5 import java.lang.reflect.InvocationTargetException;
6 import java.lang.reflect.Method;
7 import java.lang.reflect.Modifier;
9 import kotlin.Deprecated;
10 import kotlin.ReplaceWith;
13 * Utilities for testing.
15 public class TestUtil {
17 @Deprecated(message = "It only checks the given class, not its superclasses.", replaceWith = @ReplaceWith(imports = { "net.pterodactylus.sone.test" }, expression = "setField(`object`, fieldName, value)"))
18 public static void setFinalField(Object object, String fieldName, Object value) {
20 Field clientCoreField = object.getClass().getField(fieldName);
21 clientCoreField.setAccessible(true);
22 Field modifiersField = Field.class.getDeclaredField("modifiers");
23 modifiersField.setAccessible(true);
24 modifiersField.setInt(clientCoreField, clientCoreField.getModifiers() & ~Modifier.FINAL);
25 clientCoreField.set(object, value);
26 } catch (NoSuchFieldException | IllegalAccessException e) {
27 throw new RuntimeException(e);
31 public static <T> T getPrivateField(Object object, String fieldName) {
33 Field field = object.getClass().getDeclaredField(fieldName);
34 field.setAccessible(true);
35 return (T) field.get(object);
36 } catch (NoSuchFieldException | IllegalAccessException e) {
37 throw new RuntimeException(e);
41 public static <T> T callPrivateMethod(Object object, String methodName) {
43 Method method = object.getClass().getDeclaredMethod(methodName, new Class[0]);
44 method.setAccessible(true);
45 return (T) method.invoke(object);
46 } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
47 throw new RuntimeException(e);
51 public static <T> T createObject(Class<T> clazz, Class[] parameterTypes, Object... arguments) {
53 Constructor<T> constructor = clazz.getDeclaredConstructor(parameterTypes);
54 constructor.setAccessible(true);
55 return constructor.newInstance(arguments);
56 } catch (NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException e) {
57 throw new RuntimeException(e);