• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2007 Mockito contributors
3  * This program is made available under the terms of the MIT License.
4  */
5 package org.mockito.internal.util.reflection;
6 
7 import java.lang.reflect.Field;
8 
9 public class Whitebox {
10 
getInternalState(Object target, String field)11     public static Object getInternalState(Object target, String field) {
12         Class<?> c = target.getClass();
13         try {
14             Field f = getFieldFromHierarchy(c, field);
15             f.setAccessible(true);
16             return f.get(target);
17         } catch (Exception e) {
18             throw new RuntimeException("Unable to set internal state on a private field. Please report to mockito mailing list.", e);
19         }
20     }
21 
setInternalState(Object target, String field, Object value)22     public static void setInternalState(Object target, String field, Object value) {
23         Class<?> c = target.getClass();
24         try {
25             Field f = getFieldFromHierarchy(c, field);
26             f.setAccessible(true);
27             f.set(target, value);
28         } catch (Exception e) {
29             throw new RuntimeException("Unable to set internal state on a private field. Please report to mockito mailing list.", e);
30         }
31     }
32 
getFieldFromHierarchy(Class<?> clazz, String field)33     private static Field getFieldFromHierarchy(Class<?> clazz, String field) {
34         Field f = getField(clazz, field);
35         while (f == null && clazz != Object.class) {
36             clazz = clazz.getSuperclass();
37             f = getField(clazz, field);
38         }
39         if (f == null) {
40             throw new RuntimeException(
41                     "You want me to set value to this field: '" + field +
42                     "' on this class: '" + clazz.getSimpleName() +
43                     "' but this field is not declared withing hierarchy of this class!");
44         }
45         return f;
46     }
47 
getField(Class<?> clazz, String field)48     private static Field getField(Class<?> clazz, String field) {
49         try {
50             return clazz.getDeclaredField(field);
51         } catch (NoSuchFieldException e) {
52             return null;
53         }
54     }
55 }