Avoiding sun.misc.Unsafe and embracing modules in Java libraries: missing links

Michael Rasmussen Michael.Rasmussen at roguewave.com
Wed Apr 4 13:27:18 UTC 2018

I can echo a lot of what Rafael said.

JRebel is also a heavy user of the mentioned APIs here, especially Unsafe.defineClass and Unsafe.allocateInstance -- we actually use all 4 ways mentioned for creating an instance without calling the constructor (depending on Java version and vendor).
Like testing frameworks, JRebel is also something minded for a development environment, and not a production environment.
Yes, JRebel can be quite invasive with how we instrument things, and if no official API exists for doing these things, we generally dig in the private APIs until we find it; but an official supported API would always be preferable and to me the Instrumentation API does seems like a good fit for this kind of API. 

One of the main things about Unsafe.defineClass is that it can define classes in the boot (null) classloader (and in any package). We use this since we sometimes need to define companion classes in the same package as an existing on, including classes defined in the boot classloader.


From: jigsaw-dev <jigsaw-dev-bounces at openjdk.java.net> on behalf of Jochen Theodorou <blackdrag at gmx.org>
Sent: 04 April 2018 01:24
To: jigsaw-dev at openjdk.java.net
Subject: Re: Avoiding sun.misc.Unsafe and embracing modules in Java libraries: missing links

On 03.04.2018 21:26, Henri Tremblay wrote:
> For completeness, there are 4 ways to create a class without calling a
> constructor right now that I'm aware of:
>     - Unsafe.allocateInstance

which is supposed to go away at some point

>     - sun.reflect.ReflectionFactory.newConstructorForSerialization (my
>     favorite because it's the fastest one)

which afaik works in java9 but is also one of those critical doomed APIs

>     - Generate an extending class forgetting to call the super constructor
>     (so it's not exactly that same class that is instantiated). It requires
>     -Xverify:none

Is this really an option for a production environment?

>     - Generate a class extending MagicAccessorImpl that will then
>     instantiates the wanted class but calling the wrong constructor

Is jdk.internal.reflect.MagicAccessorImpl still usable in Java9+? I 
thought this is no longer exported

Under the premise that all critical API usages will be removed in the 
future and replacement APIs will be created I think we might indeed 
still miss something here

bye Jochen

More information about the jigsaw-dev mailing list