Replacing Unsafe.allocateInstance

Paul Sandoz paul.sandoz at
Tue Jun 30 09:22:01 UTC 2015

Hi Henri,

Thanks for raising this discussion.

Just to augment what Chris says here.

We cannot directly expose Unsafe.allocateInstance in a public API and try and place in a little known corner and hope only the people who are meant to use it will and will do so responsibly :-)

There are a bunch of general use-cases:

  1) Mocking;
  2) Proxying; and
  3) Serialization.

It should be possible to corral 3 (and possibly 2) in some safe mechanism. I dunno how to do that for 1.

Constructing an object without calling its constructor is inherently integrity busting (unless somehow hidden or contained) and IIUC mocking by design is a form of semi-controlled integrity busting.

Would i be correct in assuming that mocking is primarily used for testing and that if used in production would raise some eye brows?

One approach we could consider for 1, trying to be pragmatic and recognising the reality here, is a method that constructs an object without calling it's constructor under the following conditions:

1) a security check is performed if a security manager is present; and

2) it would not be possible to construct any JDK class (e.g. classes loaded by the boot loader).

That is not a definite proposal but i would be really interested in your feedback given your experience with Objenesis and mocking.


More information about the jdk9-dev mailing list