了解Java中的ClassLoader [英] Understanding ClassLoaders in Java

查看:93
本文介绍了了解Java中的ClassLoader的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对JVM和ClassLoader还是很陌生.我有这两节课:

I'm fairly new to the JVM and ClassLoaders. I have these two classes:

public abstract class CoreModule extends Entity

public final class EventManager extends CoreModule

在程序开始时,我创建一个EventManager的实例.因此,我知道JVM知道Entity类是什么以及如何加载它(也就是说,它知道要使用什么ClassLoader),因为EventManager是孙子.但是,当Entity实例通过某种序列化机制传递时,它将抛出ClassNotFoundException.我必须手动设置要使用的ClassLoader(Event.class.getClassLoader()).

At the start of the program, I create an instance of EventManager. So I understand that the JVM knows what Entity class is and how to load it (that is, it knows what ClassLoader to use), since EventManager is a grand-child. But when an Entity instance is passed by some serialization mechanism, it throws ClassNotFoundException. I have to manually set the ClassLoader to use (Event.class.getClassLoader()).

为什么JVM不知道什么是Event类,或者如果已经做到了,该如何加载呢?

How come the JVM does not know what Event class is or how to load it if it already did it?

推荐答案

实际上,JVM并没有神奇地"弄清楚这一点. 它们全部基于系统类加载器,该类将根据您使用的环境而有所不同.然后,每个线程都有一个上下文类加载器,该类从该类自动派生.

Actually the JVM does not figure this out "magically". It is all based on a system class loader which will vary depending on the environment you use. Then each thread has a context ClassLoader which derives from this automatically.

您可以使用如果您的序列化代码应该能够解析从上下文ClassLoader中看不到的类,则需要按照您的方式进行设置.

If your serialization code should be able to resolve a class not visible from the context ClassLoader you need to set this the way you did.

这篇关于了解Java中的ClassLoader的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆