简体   繁体   中英

Java reflection: How can I load a class from another project without adding that project or JAR to my classpath?

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?

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");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM