Java reflection

How to test private methods? One solution is using java reflection, here is a utility class defining a static method, wich allows invocation to the private mehods we want to test.

package org.marwan.alephn.test.utilities;

import java.lang.reflect.Method;

/**
* A class with reflection utilities for testing private methods
*/
public class ReflectUtilities
{

/**
* To be used in case of need to test private methods with
* return type, a cast to the type
* @param aClass
* Name of the class witch declares the method to be invoked
* @param instance
* An instance of a aClass
* @param aMethod
* Name of the method to invoke
* @param params
* Class type of the parameter of the method to invoke
* @param args
* Arguments for the method to invoke
* @return Object to be cast to the return type of the method invoked
* @throws Exception
* If error
*/
public static Object invoke(final Class aClass, final Object instance,
final String aMethod, final Class[] params, final Object[] args)
throws Exception
{
Object o = null;
try
{
final Method m = aClass.getDeclaredMethod(aMethod, params);
m.setAccessible(true);
o = m.invoke(instance, args);
}
catch (final Exception e)
{
throw e;
}
return o;
}

}

Good and quick reference to check for java reflection uses:


Comentarios