如果我有一个包含许多类的jar文件,如何获取类以及在运行时创建实例。在这段代码中,我不理解Class.forName行,MyClass是包含jar文件的类,还是加载jar文件后将创建的类?
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
加载一个类。
第一个参数是类的(规范)名称。在这种情况下,您尝试加载类com.MyClass
。
第二个参数指定应在该点初始化类(初始化static
变量并运行static
块。
第三个参数是将要从中加载类的ClassLoader
。在您的情况下,它将尝试从myJar
中找到该类,但是如果在那里找不到该类,它将尝试从已加载调用类的同一ClassLoader
中加载该类。