Java ClassLoader动态加载外部java代码

来源:互联网 发布:雷特字幕mac 编辑:程序博客网 时间:2024/05/15 15:40

外部代码

package priv.tuyou;public class Say {public void say(){System.out.println("say priv.tuyou.hello");}}

存放路径


动态加载示例
import java.io.ByteArrayOutputStream;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.IOException;import java.io.InputStream;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;public class PathClassLoader extends ClassLoader{private String classPath;public PathClassLoader(String classPath){this.classPath = classPath;}@Overrideprotected Class<?> findClass(String arg0) throws ClassNotFoundException {byte[] data = getData(arg0);if(data == null){throw new ClassNotFoundException();}return defineClass(arg0, data, 0, data.length);}private byte[] getData(String className){String path = classPath + File.separatorChar + className.replace(".", File.separator) + ".class";try {InputStream is = new FileInputStream(path);ByteArrayOutputStream out = new ByteArrayOutputStream();byte[] buffer = new byte[1024];int count = 0;while((count = is.read(buffer)) != -1){out.write(buffer, 0, count);}return out.toByteArray();} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}return null;}/** * 使用同一个ClassLoader重复加载一个类会报错 * @author:涂有 * @date 2017年3月3日 下午1:38:05 */public static void main2(String[] args) throws ClassNotFoundException, SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException, InstantiationException {PathClassLoader loader = new PathClassLoader("/Users/apple/temp");//第一次加载Class say = loader.findClass("priv.tuyou.Say");Method method = say.getMethod("say");Object instance = say.newInstance();method.invoke(instance);//第二次加载,报错//java.lang.LinkageError: loader (instance of  PathClassLoader): attempted  duplicate class definition for name: "Say"Class say2 = loader.findClass("priv.tuyou.Say");Method method2 = say2.getMethod("say");Object instance2 = say2.newInstance();method2.invoke(instance2);}/** * 重新new一个ClassLoader加载同一个类不会报错 * @author:涂有 * @date 2017年3月3日 下午1:38:53 */public static void main(String[] args) throws ClassNotFoundException, SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException, InstantiationException {//第一次加载PathClassLoader loader = new PathClassLoader("/Users/apple/temp");Class say = loader.findClass("priv.tuyou.Say");Method method = say.getMethod("say");Object instance = say.newInstance();method.invoke(instance);//第二次加载,不会报错PathClassLoader loader2 = new PathClassLoader("/Users/apple/temp");Class say2 = loader2.findClass("priv.tuyou.Say");Method method2 = say2.getMethod("say");Object instance2 = say2.newInstance();method2.invoke(instance2);System.out.println(instance == instance2);}}


原创粉丝点击