1 自定义ClassLoader类:MemoryClassLoader
public class MemoryClassLoader extends URLClassLoader {
// class name to class bytes:
Map<String, byte[]> classBytes = new HashMap<String, byte[]>();
public MemoryClassLoader(Map<String, byte[]> classBytes) {
super(new URL[0], MemoryClassLoader.class.getClassLoader());
this.classBytes.putAll(classBytes);
}
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
byte[] buf = classBytes.get(name);
if (buf == null) {
return super.findClass(name);
}
classBytes.remove(name);
return defineClass(name, buf, 0, buf.length);
}
}
2 封装方法、调用
/**
* Load class from compiled classes.
*
* @param name
* Full class name.
* @param classBytes
* Compiled results as a Map.
* @return The Class instance.
* @throws ClassNotFoundException
* If class not found.
* @throws IOException
* If load error.
*/
public Class<?> loadClass(String name, Map<String, byte[]> classBytes) throws ClassNotFoundException, IOException {
try (MemoryClassLoader classLoader = new MemoryClassLoader(classBytes)) {
return classLoader.loadClass(name);
}
}