ClassUtil { public static Object getPrivateFieldValue(Object object, String fieldName) { return getPrivateFieldValue(object.getClass(), object, fieldName); }  @SuppressWarnings("unchecked") static Class<T> forName(String className, Class<T> instanceOfClass); static T newInstance(Class<T> clazz); static Object getPrivateFieldValue(Object object, String fieldName); static Object getPrivateFieldValue(Class<?> clazz, Object object, String fieldName);  }
@Test public void testPrivateField() throws Exception { TestClass1 testClass1 = new TestClass1(); TestClass2 testClass2 = new TestClass2(); assertThat(ClassUtil.getPrivateFieldValue(testClass1, "field1")).isEqualTo("1"); assertThat(ClassUtil.getPrivateFieldValue(testClass2, "field2")).isEqualTo("2"); assertThat(ClassUtil.getPrivateFieldValue(testClass2, "field1")).isEqualTo("1"); try { ClassUtil.getPrivateFieldValue(testClass2, "fieldXY"); fail("should throw exception"); } catch (Exception e) { } }