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;
10 * Utilities for testing.
12 public class TestUtil {
14 public static void setFinalField(Object object, String fieldName, Object value) {
16 Field clientCoreField = object.getClass().getField(fieldName);
17 clientCoreField.setAccessible(true);
18 Field modifiersField = Field.class.getDeclaredField("modifiers");
19 modifiersField.setAccessible(true);
20 modifiersField.setInt(clientCoreField, clientCoreField.getModifiers() & ~Modifier.FINAL);
21 clientCoreField.set(object, value);
22 } catch (NoSuchFieldException | IllegalAccessException e) {
23 throw new RuntimeException(e);
27 public static <T> T getPrivateField(Object object, String fieldName) {
29 Field field = object.getClass().getDeclaredField(fieldName);
30 field.setAccessible(true);
31 return (T) field.get(object);
32 } catch (NoSuchFieldException | IllegalAccessException e) {
33 throw new RuntimeException(e);
37 public static <T> T callPrivateMethod(Object object, String methodName) {
39 Method method = object.getClass().getDeclaredMethod(methodName, new Class[0]);
40 method.setAccessible(true);
41 return (T) method.invoke(object);
42 } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
43 throw new RuntimeException(e);
47 public static <T> T createObject(Class<T> clazz, Class[] parameterTypes, Object... arguments) {
49 Constructor<T> constructor = clazz.getDeclaredConstructor(parameterTypes);
50 constructor.setAccessible(true);
51 return constructor.newInstance(arguments);
52 } catch (NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException e) {
53 throw new RuntimeException(e);