MENU

动态加载Class

May 15, 2022 • 学习笔记

动态加载class文件

编写两个java类

image-20191227094310685

image-20191227094352211

使用javac命令生成.class文件

javac RelationClass1.java RelationClass2.java

image-20191227094435345

代码部分

加载File
File file1 = new File("D:\\CodeProjects\\IdeaProjects\\Test\\src\\com\\sundae\\test\\dynamicloadclass\\RelationClass1.class");
File file2 = new File("D:\\CodeProjects\\IdeaProjects\\Test\\src\\com\\sundae\\test\\dynamicloadclass\\RelationClass2.class");
转换成URL

URL需要加前缀file:/

URL[] urls = new URL[]{new URL("file:/"+file1.toString()), new URL("file:/"+file2.toString())};
使用URLClassLoader加载
URLClassLoader urlClassLoader = new URLClassLoader(urls);
Class clz1 = urlClassLoader.loadClass(getClass().getPackage().getName() + "." + "RelationClass1");
Class clz2 = urlClassLoader.loadClass(getClass().getPackage().getName() + "." + "RelationClass2");
使用反射调用
Object clz1Instance = clz1.newInstance();
Method method = clz1.getMethod("hello", String.class);
Object result = method.invoke(clz1Instance, "loadRelationClass()");
System.out.println(result);        

结果

image-20191227095006239