Re: dealing with ClassLoaders...
Eric Sosman <esosman@comcast-dot-net.invalid> wrote:
On 8/1/2014 5:10 PM, Andreas Leitgeb wrote:
Andreas Leitgeb <avl@auth.logic.tuwien.ac.at> wrote:
Martin Gregorie <martin@address-in-sig.invalid> wrote:
public class MAClassLoader extends ClassLoader
{
[ no snip ]
}
I hope this is useful info.
On further examination, I think it isn't as simple as that.
Essentially, this "empty" ClassLoader-subclass would pass
everything through to the parent classloader (or the pre-
mordial one, absent a parent) and thus not be associated to
any of the classes loaded through it, thus provide no
isolation at all.
That conclusion may be worth re-examining. Just because
MAClassLoader is a subclass of ClassLoader and uses methods
of the latter to do all its dirty work, it doesn't mean the
classes aren't loaded by MAClassLoader.
You're right about the "Just because ...": That wasn't the ground for
my claim. Instead, I drew my conclusion from what ClassLoader's
javadoc says about its own default implementation of findClass(),
namely: "The default implementation throws a ClassNotFoundException."
This (plus the documentation of loadClass()) means that any classname
passed to that class's loadClass() either gets loaded by its parent (not
in terms of inheritence, but in terms of ClassLoader.getParent()!) or it
inevitably will fail to be loaded at all.
There is a big difference between merely letting some superclass methods
do some work (which could still affect "this" instance), versus knowing
(from docs) that these superclass methods' work is merely delegating work
to a different *instance*, namely the ClassLoader's getParent().
It must be admitted, though, that ClassLoader is a bit
weird. An abstract class all of whose methods are concrete?
I think that's to allow the choice for which method to actually override,
without having to care about then-never-used dummy implementations of other
methods.
Normally, one would override findClass(), but if one overrides loadClass()
instead, and doesn't need findClass() in his implementation, then he doesn't
need to "implement" findClass().
FWIW, I have successfully used
private static class Loader extends ClassLoader {
private Class<?> load(byte[] classFile) {
Class<?> clown = defineClass(
null, classFile, 0, classFile.length);
resolveClass(clown);
return clown;
}
}
This is obviously quite different from Martin's MAClassLoader, in
that your Loader instance itself does the defineClass() call and
thus the loaded class is associated with your Loader instance.
... to load many distinct classes with identical package and
class names, which suggests there's at least some degree of
isolation present even though all the actual work is done by
ClassLoader itself.
In your code work is done in the instance itself, not delegated
to a *different* ClassLoader-*instance*.