java - Loading classes not present in the classpath -
Assume that I've compiled a Groovy script using Grovik, which has one or more classes in the file system. Files are generated. From the Java application, how do I add those classes to dynamically by loading them and how to call them? The goal is to compile the Groovy script first and store it in the database, so the compilation versions of the scripts can be evaluated.
You can create an example of loading 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 loaded class = cl.loadClass ("com.xyz.MyClass"); MyClass obj = (MyClass) loadedClass.newInstance (); Obj.doSomething ();
Line 1 creates that code as URL
where. Class files remain.
Line 2 creates a new URLClassLoader
Example The first argument is an array of URLs to be used as source. You can specify several directory URLs within the array. The second argument is the Classloader, which will become the parents of this new ClassLoder. We execute the code above class as this argument in the class code.
The child classloader loaded by class classmates can access classes loaded by classloader.