简体   繁体   中英

How to load .class and call one of its methods

I've compiled at runtime a java file on file system which is a very simple class:

public class Test {

public static int res(int a, int b) {   
    return a*b;
}   

}

now I just want to call res method from my project (that will be a jar), but my code produce java.lang.ClassNotFoundException: Test

and this is how I've loaded the class:

URL[] urls = new URL[] {new URL("file:///"+UtilOverriding.getFile1().replace("java", "class"))};
        URLClassLoader loader = new URLClassLoader(urls);
        Class clazz = loader.loadClass("Test");

When you specify a class path you have to provide the directory which is the parent to all your packages. Try instead.

 new URL("file:///"+UtilOverriding.getFile1().getParent()}

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