0

I've searched some topics, but couldn't find the answer. What i need is just to set up an additional path for default ClassLoader.

Right now i have such class:

public class Loader extends ClassLoader {

public void setPath(String s) {
File file = new File(s);
try {
            URL classUrl = file.toURI().toURL();
            URL[] urls = new URL[]{classUrl};
            ClassLoader ucl = new URLClassLoader(urls);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
}

And i need to make method setPath to work in such a way:

Loader load = new Loader();
load.setPath(directoryName);
Class clazz = (ClassLoader) load.loadClass(className);

Can someone help me in achieving this? Thanks.

NREZ
  • 942
  • 9
  • 13
qiGuar
  • 1,726
  • 1
  • 18
  • 34
  • Well, you can do this: http://stackoverflow.com/a/16335435/1003886 – kajacx Jul 18 '13 at 13:19
  • Not exactly what i'm looking for. I'd like to make it work as i mentioned above. Is it even possible at all? – qiGuar Jul 18 '13 at 17:22
  • Then you can store the path in a field in `Loader` and override the `loadClass()` method with the code from my previous comment with the stored path. – kajacx Jul 18 '13 at 17:49

1 Answers1

1

Why not just make a new method to load a class from a specific path? Don't forget to set a parent on the URL classloader, otherwise it will not be able to load dependent classes from the JDK.

public class Loader {
    public Object loadClass(String path, String classname) {
        File file = new File(path);
        try {
            URL classUrl = file.toURI().toURL();
            URL[] urls = new URL[]{classUrl};
            ClassLoader ucl = new URLClassLoader(urls, getClass().getClassLoader());
            return ucl.loadClass(classname);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
Byron Hawkins
  • 2,536
  • 2
  • 24
  • 34