I am currently learning about the Dirac formalism in quantum mechanics, but don't quite understand how we derive the expression of the quantum Hamiltonian, given the value of energy in classical mechanics.
The specific example that came up in class was that of the harmonic oscillator, for which the classical energy is $$E = \frac{p^2}{2m} + \frac{1}{2}m\omega^2x^2$$
My teacher then concluded that
$$\hat{H} = \frac{\hat{p}^2}{2m} + \frac{1}{2}m\omega^2\hat{x}^2$$
Why is that? The only way I see to show this is by looking at a stationary wave function $\psi (x)$ and using the associated Schrödinger equation. We get get that, by writing $V(x) = \frac{1}{2}m\omega^2x^2$,
$$E\psi(x) = \frac{-\hbar^2}{2m}\frac{d^2\psi(x)}{dx^2} + V(x)\psi = \hat{H}\psi(x)$$
By identifying known expressions for $\hat{p}$ and $\hat{x}$, we can find the desired expression for the Hamiltonian. However, I do not feel like this method is very satisfying, as it requires to return to wave functions, and doesn't use the Schrödinger equation in the Dirac formalism.
I am getting a feeling that teachers will eagerly replace $x$ by $\hat{x}$ and p by $\hat{p}$ when going from classical mechanics to quantum mechanics.
Is there a more general result? Can it be said that if in classical mechanics $E = f(x_1, \dots, x_n)$ where $x_1, \dots, x_n$ are observables, then $\hat{H} = f(\hat{x_1},\dots,\hat{x_n})$? I cannot see why that would be true, so is it only a coincidence that it is true in the case of the harmonic oscillator?
To summarize, is there a rule for when such replacements are valid, and if so, for which observables and how can it be proven?