如何在JVM中再加载一次java.util.TimeZone [英] How to load java.util.TimeZone more then once in JVM

查看:68
本文介绍了如何在JVM中再加载一次java.util.TimeZone的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了自定义类加载器:

I create my custom class loader :

new URLClassLoader(urls, Thread.currentThread().getContextClassLoader());

其中url是一个新Url("java.util.TimeZone")

之后,我按名称加载课程:

After that I load class by name :

Class<?> newTimeZoneClass = loader.loadClass("java.util.TimeZone");

newTimeZoneClass == TimeZone.class 返回 true .

我的类加载器从父加载器加载类的主要原因.如何解决?

The main reason of that my class loader load class from parent loader. How to fix it?

推荐答案

您不能执行此操作.Java安全模型可防止任何类加载器在"java.*"层次结构中创建类.这是用JVM的本机代码硬编码的,因此没有解决方法.

You cannot do this. The Java security model prevents any class loader creating a class in the "java.*" hierarchy. This is hard-coded in the native code of the JVM, so there is no workaround.

此外,标准类加载器遵循委托模型,要求父类加载器在尝试加载类之前先进行加载,因此您始终会获得相同的类实例.应用程序容器使用特殊的类加载器来反转针对特定于应用程序的类的委派.

Additionally, the standard class loaders follow the delegation model of asking the parent class loader to load the class before they try to, so you always get the same class instance. Special class loaders are used by application containers to invert this delegation for application specific classes.

反正有几种方法.

首先, TimeZone 是一个抽象类,实际的实现通常是 sun.util.calendar.ZoneInfo .由于这不在"java.*"层次结构中,因此您可以在类加载器中创建多个副本.

First, TimeZone is an abstract class and the actual implementation is normally sun.util.calendar.ZoneInfo. As this is not in the "java.*" hierarchy, you can create multiple copies in your class loaders.

第二,您可以对 TimeZone 进行子类化,并将所有方法委托给JVM提供的实例,同时添加自己的功能.我已经使用它使TimeZone实例在我的某些应用程序中成为单例.

Second, you can sub-class TimeZone, and delegate all methods to a JVM provided instance, adding your own functionality as you do so. I've used this to make TimeZone instances singletons in some of my applications.

第三,由于JDK是开源的,因此您可以将 TimeZone 的所有代码及其子类复制到您自己的应用程序中,然后可以使用与你喜欢.

Third, as the JDK is open source, you can copy the all the code for TimeZone and its sub-classes into your own application, and then you can have as many versions of the class as you like.

如果要更改 TimeZone 中的静态方法返回的 TimeZone 实例,则这些实例将委托给 ZoneInfo 使用反思来改变结果.如果您知道Aspect-J或同等学历,则也可以拦截该呼叫.

If you want to change the TimeZone instances returned by the static methods in TimeZone, these delegate to ZoneInfo and you will have to either use reflection to change the outcome. If you know Aspect-J or equivalent, you could also intercept the call.

这篇关于如何在JVM中再加载一次java.util.TimeZone的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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