d33028183bcb324f20c0b629102639b4a07e62bb
[Sone.git] / src / test / java / net / pterodactylus / sone / test / TestUtil.java
1 package net.pterodactylus.sone.test;
2
3 import java.lang.reflect.Field;
4 import java.lang.reflect.InvocationTargetException;
5 import java.lang.reflect.Method;
6 import java.lang.reflect.Modifier;
7
8 /**
9  * Utilities for testing.
10  */
11 public class TestUtil {
12
13         public static void setFinalField(Object object, String fieldName, Object value) {
14                 try {
15                         Field clientCoreField = object.getClass().getField(fieldName);
16                         clientCoreField.setAccessible(true);
17                         Field modifiersField = Field.class.getDeclaredField("modifiers");
18                         modifiersField.setAccessible(true);
19                         modifiersField.setInt(clientCoreField, clientCoreField.getModifiers() & ~Modifier.FINAL);
20                         clientCoreField.set(object, value);
21                 } catch (NoSuchFieldException e) {
22                         throw new RuntimeException(e);
23                 } catch (IllegalAccessException e) {
24                         throw new RuntimeException(e);
25                 }
26         }
27
28         public static <T> T getPrivateField(Object object, String fieldName) {
29                 try {
30                         Field field = object.getClass().getDeclaredField(fieldName);
31                         field.setAccessible(true);
32                         return (T) field.get(object);
33                 } catch (NoSuchFieldException e) {
34                         throw new RuntimeException(e);
35                 } catch (IllegalAccessException e) {
36                         throw new RuntimeException(e);
37                 }
38         }
39
40         public static <T> T callPrivateMethod(Object object, String methodName) {
41                 try {
42                         Method method = object.getClass().getDeclaredMethod(methodName, new Class[0]);
43                         method.setAccessible(true);
44                         return (T) method.invoke(object);
45                 } catch (NoSuchMethodException e) {
46                         throw new RuntimeException(e);
47                 } catch (InvocationTargetException e) {
48                         throw new RuntimeException(e);
49                 } catch (IllegalAccessException e) {
50                         throw new RuntimeException(e);
51                 }
52         }
53
54 }