Upon further testing, this turns out to be less capable than the “Unsafe” 
version - in particular, I cannot create a test stub in a closed package. The 
problem is that unit tests often need to do a number of things like this that 
make no sense in a production environment. 

The problem has to do with creating test stubs to take the place of JDK 
objects. In many cases, this requires access to package-protected classes or 
fields, as the JDK doesn’t provide clean interfaces for a lot of its 
functionality. In the past, we could do this by defining a subclass in the same 
package as the JDK class we needed to stub. That no longer works without 
command-line switches. Related to this, unit tests must often create stub 
classes specifically in thread context class loaders - but those classes are 
frequently not in the same package as the test code. This new feature doesn’t 
support that at all, and I don’t even see a way to use a command line switch to 
enable it.

- Russ

> On Mar 14, 2017, at 4:47 PM, Alan Bateman <alan.bate...@oracle.com> wrote:
> 
> On 14/03/2017 17:37, Russell Gold wrote:
>> Hi Alan,
>> 
>> I am trying this in SimpleStub, and it seems to work for my current test 
>> cases if I do this:
>>> MethodHandles.Lookup in = MethodHandles.privateLookupIn( baseClass, 
>>> MethodHandles.lookup() ).dropLookupMode( MethodHandles.Lookup.PRIVATE );
>>> return in.defineClass(classBytes);
>> 
>> My tests create stubs from public, package-private and protected classes. Is 
>> that what you are expecting? It seems a bit overly complex. 
> You get a full-power lookup on the "baseClass", passing your own lookup that 
> proves you have access. Then you drop private access as it's not supported by 
> defineClass at this time. So it looks right.
> 
> 
>> 
>> In gmbal, I see that this may not suffice, as the current interfaces provide 
>> no way to supply a class to use as a base. Figuring out how those interfaces 
>> are being used might change my answer.
>> 
> Could you add an overloaded register method to ManagedObjectManager to take 
> the Lookup?
> 
> -Alan

Reply via email to