Search code examples
javareflectionclasspathclassloader

Does a .class file on disk have to follow the same directory structure as its qualified name in Java for us to run it?


After reading about dynamic class loading (that is, loading a .class file from disk) I am getting a bit worried.

Let's say I have a file called MyClass.class that contains the class a.b.c.MyClass. Assuming I now decide to move the file to C:\(my root folder in Windows), I'd like to dynamically load this class. Is that possible, at all? From what I understood it seems MyClass' path would always have to be of the form *a/b/c.MyClass.

Thus, the following bit of code doesn't seem to work:

URL[] urls = new URL[] { new File("C:\\").toURL() };
URLClassLoader classLoader = new URLClassLoader(urls);
Class<?> targetClass = classLoader.loadClass("a.b.c.MyClass");

Forcing us to put a .class file in a directory structure that reflects its full internal name is insane, IMO. Am I missing something?

A possible implication of this fact would be that if I decide to copy a couple of .class files into a temporary directory so I can perform some awesome wizardry over them, I'll have to replicate all their dirty paths in that same temporary directory, which is awkward, at best.


Solution

  • Does a .class file on disk have to follow the same directory structure as its qualified name in Java for us to run it?

    Yes, if you are using the standard classloaders.

    In theory, you could implement a custom classloader that used a different scheme for locating the class files. But there's a good chance that you would run into problems when (for example) debugging your code. So I wouldn't recommend it.