0

Here's my situation: I have a class in project A. I want to load this class in a method in project B without adding project A (or a JAR containing the class) to my project B classpath (I personally have no objection to doing it that way, but I must build this to spec).

Note that I will not know the absolute path to this class (let's call it "MyClass") as project A may be installed various different locations. I will, however, know how to navigate to it based on my current directory, so that is what I have done.

Here is what I have tried:

// Navigate to the directory that contains the class
File pwd = new File(System.getProperty("user.dir"));
File src = pwd.getAbsoluteFile().getParentFile();
File dir = new File(src.getAbsolutePath() + File.separator + "folder" + File.separator + "src");
// dir is the directory that contains all the packages of project A

// Load the class
URLClassLoader classLoader = URLClassLoader.newInstance(new URL[] {dir.toURI().toURL()});

try {
    classLoader.loadClass("com.blahblahblah.MyClass");
} catch (ClassNotFoundException exception) {
}

This throws a ClassNotFoundException. Am I doing something wrong?

user1015721
  • 149
  • 1
  • 7
  • 1
    First, is the ".class" file really in your src/ folder? Your 'dir' file currently points to a src/ folder. – Keith Jun 11 '13 at 02:42
  • Note that this: `new File(src.getAbsolutePath() + File.separator + "folder" + File.separator + "src")` Can be simplified to this: `new File(src, "folder/src")` – Keith Jun 11 '13 at 02:45
  • I do it like this for me `File file = new File(dirPath + filieName); URL url = file.getCanonicalFile().toURI().toURL(); URLClassLoader classLoader = new URLClassLoader(new URL[]{url});` – cpz Jun 11 '13 at 02:47
  • And the dirPath is fetched like this `String dirPath = System.getProperty("user.dir") + File.separator + JAR_DIR + File.separator;` – cpz Jun 11 '13 at 02:49

1 Answers1

0

You need to implement a custom classloader, something like this

    Class<?> cls = new ClassLoader() {
        public java.lang.Class<?> loadClass(String name) throws ClassNotFoundException {
            byte[] a = read class bytes from known location
            return defineClass(name, b, 0, a.length);
        };
    }.loadClass("test.MyClass");
Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275