如何构建同一个加载不同类加载器的两个实例? [英] How to cast two instance of the same loaded different classloader?

查看:219
本文介绍了如何构建同一个加载不同类加载器的两个实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个不同的webapps,每个都加载相同的A类和不同的classloader。当我在会话中放入一个实例然后从另一个webapp获取它时,抛出 ClassCastException

I have two different webapps, and each load the same class A with different classloader. When I put one instance in the session and then get it from the other webapp, a ClassCastException is thrown.

例如,在webapp A中,我在会话中存储 a ,然后在webapp B中,我得到 a 会话并将其转换为A,抛出 ClassCastException

For example, in webapp A, I store a in the session, then in webapp B, I get the a from the session and cast it to A, the ClassCastException is thrown.

有没有办法解决这个问题?

Is there a way to resolve this?

推荐答案


有没有办法解决这个问题?

Is there a way to resolve this?

基本上没有。

就JLS而言,类型是不同的类型,并且没有办法JVM将允许您以其他方式假装。例如,类可以具有不同的代码和不同的对象布局。如果您可以欺骗JVM将类型视为相同类型,那么您将能够吹走JVM运行时的安全性。这种方式就是疯狂。

As far as the JLS is concerned, the types are different types, and there is no way that the JVM will allow you to pretend otherwise. For instance, the classes could have different code and different object layouts. If you could trick the JVM into treating the types as the same, you would be able to blow away JVM runtime safety. That way lies insanity.

解决方案是确保你没有两个不同的类加载器加载同一个类。在Tomcat的上下文中,这意味着如果两个或更多webapp需要共享一个类的实例,那么该类必须在两个共同的类加载器中定义;例如将JAR文件放在 $ CATALINA_HOME / lib $ CATALINA_HOME / common 目录中。

The solution is to make sure that you don't have two different class loaders loading the same class. In the context of Tomcat, this means that if two or more webapps need to share instances of a class, then that class must be defined in a classloader that is common to both; e.g. put the JAR file in the $CATALINA_HOME/lib or $CATALINA_HOME/common directory.

如果有一个合理的原因,为什么要由不同的类加载器加载(可能是因为类真的不同),然后您可以通过定义该类的两个版本实现的接口,然后编程到接口而不是实现类来解决问题。当然,只能加载一个版本的接口......否则你会遇到同样的问题。

If there is a sound reason why the classes have to be loaded by different classloaders (maybe because the classes really are different), then you could workaround the problem by defining an interface that both versions of the class implement, and then programming to the interface rather than the implementation class. Of course, there can only be one version of that interface loaded ... or else you run into the same problem again.

这篇关于如何构建同一个加载不同类加载器的两个实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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