You can create an instance of URLClassLoader to load new classes from a directory:
URL dirUrl = new URL("file:/" + "path_to_dir" + "/"); // 1
URLClassLoader cl = new URLClassLoader(new URL[] {dirUrl},
getClass().class.getClassLoader()); // 2
Class loadedClass = cl.loadClass("com.xyz.MyClass");
MyClass obj = (MyClass) loadedClass.newInstance();
obj.doSomething();
Line 1 creates the URL
to the directory where the .class files reside.
Line 2 creates a new URLClassLoader
instance. First argument is an array of URLs to be used as the source. You can specify multiple directory URLs within the array. Second argument is the classloader that will become the parent of this new classloader. We pass the classloader of the class executing the above code as this argument.
The classes loaded by a child classloader can access the classes loaded by the parent classloader.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…