1

the problem is next: i took the base classLoader code from here. but my classLoader is specific from a point, that it must be able to load classes from a filesystem(let's take WinOS), so in classLoader must be some setAdditionalPath() method, which sets a path(a directory on a filesystem), from which we'll load class(only *.class, no jars). here is code, which modifies the loader from a link(you can see, that only loadClass is modified), but it doesn't work properly:

public void setAdditionalPath(String dir) {
            if(dir == null) {
                throw new NullPointerException("");
            }

            this.Path = dir;
        }

        public Loader(){
              super(Loader.class.getClassLoader());
        }


        public Class loadClass(String className) throws ClassNotFoundException {
          if(Path.length() != 0) {
            File file = new File(Path);

            try {
                // Convert File to an URL

         URL url = file.toURL();          
                URL[] urls = new URL[]{url};

                // Create a new class loader with the directory
                ClassLoader cl = new URLClassLoader(urls);


                ClassLoader c = cl.getSystemClassLoader();
                Class cls = c.loadClass(className);
                return cls;

            } catch (MalformedURLException e) {

            } catch (ClassNotFoundException e) {

            }

        }
            return findClass(Path);
        }

I'd grateful if anyone helps :)

5
  • What error(s), if any, are you getting. It can be hard to debug this with little-to-no information. Commented Mar 6, 2012 at 21:18
  • @Legend first i set Path value with a directory, where are some classes. then i call classloader with a class which is in this directory, but it returns an NPE(NullPointerException) at some of these lines ClassLoader cl = new URLClassLoader(urls); ClassLoader c = cl.getSystemClassLoader(); Class cls = c.loadClass(className); Commented Mar 6, 2012 at 21:36
  • i can't say my solution is correct. the main result i want to obtain is that my classloader will be able to load classes from file directory which i set in the method, otherwise, the parent classloader is called. Commented Mar 6, 2012 at 22:07
  • Don't ignore exceptions! For each catch, add e.printStackTrace(). It is no good trying to program on blind faith. Commented Mar 7, 2012 at 6:37
  • @AndrewThompson i don't ignore them as you see in the code! NPE is thrown by Class cls = c.loadClass(className); line Commented Mar 7, 2012 at 21:17

1 Answer 1

2

You can just use framework provided java.net.URLClassLoader. No need to write your own. It supports loading of classes from directories and JAR files.

Any URL that ends with a '/' is assumed to refer to a directory. Otherwise, the URL is assumed to refer to a JAR file which will be opened as needed.

It also supports a parent class loader. If this class loader does not suite your requirements, perhaps you can specify in more detail what you need. And in any case, you can look at the source and derive your own class loader class based on that.

Here is a short working snippet of code that should demostrate how to load a class by name from a URLClassLoader:

    ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader();

    // This URL for a directory will be searched *recursively*
    URL classes =
        new URL( "file:///D:/code/myCustomClassesAreUnderThisFolder/" );

    ClassLoader custom = 
        new URLClassLoader( new URL[] { classes }, systemClassLoader );

    // this class should be loaded from your directory
    Class< ? > clazz = custom.loadClass( "my.custom.class.Name" ); 
    // this class will be loaded as well, because you specified the system 
    // class loader as the parent
    Class< ? > clazzString = custom.loadClass( "java.lang.String" ); 
Sign up to request clarification or add additional context in comments.

3 Comments

so it was NPE, cause i set the path in an incorrect format? i'll try, thanks!
i don't know, but your example also returns NPE.
Tested it in a unit test, ran just fine. Edit your question post the full stack trace.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.