Ejemplo n.º 1
0
 /**
  * Invoke the specified method.
  *
  * <p>The invoker needs to have been prepared before.
  *
  * @return the object (possibly null) returned by the method invocation, or {@code null} if the
  *     method has a void return type
  * @throws java.lang.reflect.InvocationTargetException if the target method threw an exception
  * @throws IllegalAccessException if the target method couldn't be accessed
  * @see #prepare
  */
 public Object invoke() throws InvocationTargetException, IllegalAccessException {
   // In the static case, target will simply be {@code null}.
   Object targetObject = getTargetObject();
   Method preparedMethod = getPreparedMethod();
   if (targetObject == null && !Modifier.isStatic(preparedMethod.getModifiers())) {
     throw new IllegalArgumentException("Target method must not be non-static without a target");
   }
   ReflectionUtils.makeAccessible(preparedMethod);
   return preparedMethod.invoke(targetObject, getArguments());
 }
Ejemplo n.º 2
0
  @Test
  public void setField() {
    TestObjectSubclassWithNewField testBean = new TestObjectSubclassWithNewField();
    Field field =
        ReflectionUtils.findField(TestObjectSubclassWithNewField.class, "name", String.class);

    ReflectionUtils.makeAccessible(field);

    ReflectionUtils.setField(field, testBean, "FooBar");
    assertNotNull(testBean.getName());
    assertEquals("FooBar", testBean.getName());

    ReflectionUtils.setField(field, testBean, null);
    assertNull(testBean.getName());
  }