Water hammer commonly occurs when a valve is closed suddenly at an end of a pipeline system, and a pressure wave propagates in the pipe. In this case the valve will be a float (ball) valve in the toilet cistern.
If the valve does not close properly, due to it being worn or debris in the valve, then the water pressure can cause an oscillation resulting in loud vibration, banging and sometimes high pitched 'screeching' noises. The effect is made worse if pipes are not correctly secured or clipped under floorboards or within walls etc.
The offending valve needs to either be refurbished or replaced.