ReflectionHelper.class, convenient methods to work with private fields and methods. Also useful for testing purposes, etc.
ReflectionHelper.getField(myObject, "mCount"); ReflectionHelper.invoke(myObject, "notifyListeners", new Class[]{Result.class}, new Object[]{result});
public static final Object getField(final Object _obj, final String _name) throws NoSuchFieldException, IllegalAccessException {
final Field field = _obj.getClass().getDeclaredField(_name);
field.setAccessible(true);
return field.get(_obj);
}
public static final void setField(final Object _obj, final String _name, final Object _value) throws NoSuchFieldException, IllegalAccessException {
final Field field = _obj.getClass().getDeclaredField(_name);
field.setAccessible(true);
field.set(_obj, _value);
}
public static final Object invoke(final Object _obj, final String _name, @Nullable final Class[] _parameterTypes,
@Nullable final Object[] _args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
final Method method = _obj.getClass().getDeclaredMethod(_name, _parameterTypes);
method.setAccessible(true);
return method.invoke(_obj, _args);
}
Бывает, не хочется портить API ради тестирования, но нужно как-то добраться до private метода.
function callPrivateMethod($object, $method, $args)
{
$classReflection = new \ReflectionClass(get_class($object));
$methodReflection = $classReflection->getMethod($method);
$methodReflection->setAccessible(true);
$result = $methodReflection->invokeArgs($object, $args);
$methodReflection->setAccessible(false);
return $result;
}
$myObject = new MyClass();
callPrivateMethod($myObject, 'hello', ['world']);