简体   繁体   中英

How to load classes dynamically from jar file

If i have a jar file that contain many class, how to get classes, and create instances at runtime. In this code i don't understand the Class.forName line, the MyClass is that class what contain the jar file or that class what will create after the jar file load?

URLClassLoader child = new URLClassLoader(
        new URL[] {myJar.toURI().toURL()},
        this.getClass().getClassLoader()
);
Class classToLoad = Class.forName("com.MyClass", true, child);
Method method = classToLoad.getDeclaredMethod("myMethod");
Object instance = classToLoad.newInstance();
Object result = method.invoke(instance);

Class.forName loads a class.

The first parameter is the (canonical) name of the class. In this case, you try to load the class com.MyClass .

The second parameter specifies that the class should be initialized at that point( static variables are initialized and static blocks are run.

The third parameter is the ClassLoader the class will be loaded from. In your case, it will try to find the class from myJar but if the class isn't found there, it will try to load the class from the same ClassLoader the calling class has been loaded.

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