Friday, July 13, 2012

Utility methods for calling private instance methods and variables


 /**
  * This is an utility method to get value of private instance variable of a class.
  * 
  * @param classInstance
  * @param fieldName
  * @return
  * @throws SecurityException
  * @throws NoSuchFieldException
  * @throws IllegalArgumentException
  * @throws IllegalAccessException
  */
 public static Object getPrivateInstanceFieldValue(Object classInstance, String fieldName) throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
  Field field = classInstance.getClass().getDeclaredField(fieldName);
  field.setAccessible(true);
  return field.get(classInstance);
 }
 
 /**
  * This is an utility method to invoke/execute private instance method of a class.
  * 
  * Note: Make sure you pass the correct method arguments in order to invoke the correct method.
  * 
  * @param classInstance
  * @param methodName = name of the private instance method of the class whose instance is passed
  * @param methodArguments = arguments of the private instance method whose name is passed
  * @return
  * @throws IllegalArgumentException
  * @throws IllegalAccessException
  * @throws InvocationTargetException
  */
 public static Object invokePrivateInstanceMethod(Object classInstance, String methodName, Object... methodArguments) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {
  
  Method[] classMethods = classInstance.getClass().getDeclaredMethods();
  for (Method method : classMethods) {
   if(method.getName().equals(methodName) && method.getParameterTypes().length == methodArguments.length) {
    method.setAccessible(true);
    return method.invoke(classInstance, methodArguments);
   }
  }
  Assert.fail ("Method - '" + methodName +"' with passed parameters not found in class - " + classInstance.getClass().getCanonicalName());
  return null;
 }

No comments: