Search code examples
javaurlreflectionclassloader

How to load and initialize a class/jar/... at runtime even if it is out of the classPath?


I want to initialize a class that is not known during compilation (yet implementing a known interface).

So I tried something like this :

Class<?> cls = class.foreName("NotKnown",true,ClassLoader.getSystemClassLoader());

It worked in Eclipse , but as a runnable jar file I found out this won't work because it won't load a class which is out of your classPath.

How can I make it work ?


Solution

  • You need to create new classloader that would load classes from the folder where your new class is located:

    ClassLoader cl = new URLClassLoader(new URL[] { ... });
    Class<?> cls = cl.loadClass("NotKnown");
    

    I.e. if you have a class foo.bar.Baz and it was compiled to /someFolder/foo/bar/Baz.class, you should use new File("/someFolder").toURI().toURL() as a folder to load your class from.