Ensure HABTM relationships produce valid class names (Fixes #17119)

See https://github.com/rails/rails/issues/17119 for the back story.
FWIW, `ObjectSpace` is [used elsewhere in Rails](https://github.com/rails/rails/search?utf8=%E2%9C%93&q=ObjectSpace) as of the time of this comment. Not a lot, but it is there. Does Rails already require JRuby to have it turned on?