Currently Unsafe.defineAnonymousClass requires its host-class argument to be non-null. This requirement should be relaxed, so that anonymous classes can be injected into packages without *also* injecting them into the nest of a host class.
The nest-injection behavior is inappropriate when using anonymous classes for proxies.
Also, the nest-injection behavior needs to be made optional if anonymous classes are going to be loaded by untrusted code, via a Lookup API. The logic of Lookup.defineAnonymousClass is such that if the Lookup object does *not* have PRIVATE level access, it *must not* inject the anonymous class code into any other class's nest.
In order to properly specify the class loader and protection domain for a non-hosted anonymous class, the API will have to provide these values. Perhaps the best way to accomplish this is to add a new overloading (and/or flag) to Unsafe.defineAnonymousClass which uses a class argument as a "weak host", providing no nest-mate access, but only the appropriate loading context.
Unsafe.defineAnonyousClass(Class<?> hostClass, boolean addToNest, byte[] data, Object[] cpPatches)
(Until now, the workaround for the bug has been to pick a "random victim" as a host class. This is perhaps appropriate for privileged users of Unsafe, but will not work for less-privileged users such as proxy generators.)