When Java loads a class, it is in the context of a specific ClassLoader. Dependencies of that class will then be resolved by attempting to load them from that same loader. The same class might then exist in multiple unrelated loaders.

As developers using MS.hookClassLoad will typically have their extensions loaded when the VM starts into an isolated loader, it can become awkward at best and impossible at worst to directly access the classes you are attempting to hook.

This API allows you to "migrate" code to a different place in the loader hierarchy, solving this problem: in your MS.ClassLoadHook, you can get the ClassLoader of the loaded class using getClassLoader and then call this API to run code in that context.

At a low-level, this mechanism maintains ClassLoader instances for your extension at different places in the hierarchy; when you switch to a different one, the object you pass has its class changed to the equivalent code inside the new loader.

A common use for this API is to pass a Runnable instance. As that interface comes with the VM, code from both the old context will still be able to call run on the result, allowing you to continue your logic with access to different dependencies.

<T> T moveUnderClassLoader(ClassLoader loader, T object);
Parameter Description
loader The ClassLoader that has access to the types you need.
object An object whose class will be migrated to a ClassLoader underneath loader and then executed.
return This function returns the argument it is passed, in addition to modifying that argument. (This is simply for convenience.)
MS.moveUnderClassLoader(clazz.getClassLoader(),
    new Runnable() {
        public void run() {
            /* do something directly using class */
        }
    }
).run();