我使用URLClassLoader从jar文件加载类,然后我序列化这些类的对象并将其保存在文件中。然后当我去反序列化类时,ObjectInputStream会抛出一个java.lang.ClassNotFoundException,并且它没有找到我动态加载的类。我如何反序列化加载的类?
要使用自定义ClassLoader,您必须覆盖resolveClass方法。以下是JDK源代码的示例(不公开,但您可以将其用于灵感)
/**
* This subclass of ObjectInputStream delegates loading of classes to
* an existing ClassLoader.
*/
class ObjectInputStreamWithLoader extends ObjectInputStream
{
private ClassLoader loader;
/**
* Loader must be non-null;
*/
public ObjectInputStreamWithLoader(InputStream in, ClassLoader loader)
throws IOException, StreamCorruptedException {
super(in);
if (loader == null) {
throw new IllegalArgumentException("Illegal null argument to ObjectInputStreamWithLoader");
}
this.loader = loader;
}
/**
* Use the given ClassLoader rather than using the system class
*/
@SuppressWarnings("rawtypes")
protected Class resolveClass(ObjectStreamClass classDesc)
throws IOException, ClassNotFoundException {
String cname = classDesc.getName();
return ClassFinder.resolveClass(cname, this.loader);
}
}
apache commons在org.apache.commons.io.input.ClassLoaderObjectInputStream
中提供此功能。代码与彼得建议的相同,但公开
来自javadocs:
一个特殊的ObjectInputStream,它基于指定的ClassLoader而不是系统默认值来加载类。
这在动态容器环境中很有用。