Loading classes that are not in the classpath

Say I compiled a Groovy script using Groovyc, which generated one or more .class files on a file system. From a Java application, how can I add these classes to the classpath dynamically to load them and call their methods? The goal is to precompile Groovy scripts and save them in a database, so evaluation can be done from compiled versions of scripts.

+3
source share
2 answers

You can create an instance of URLClassLoader to load new classes from the 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();

1 URL , .class.

2 URLClassLoader. - URL-, . URL- . - , . , , .

, , , .

+9

.

javadoc , .

0

Source: https://habr.com/ru/post/1756835/


All Articles