在运行时更新 Java 代码 [英] Update Java code during runtime

查看:60
本文介绍了在运行时更新 Java 代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大约一年前,我偶然发现了 Java 中的一个很好的特性,我一生都找不到它.

about a year ago I stumbled across a nice feature in Java that I cannot for the life of me find again.

通过一些神奇的接口,显然可以在运行时声明一些可替换的类或函数.
我找到了一个很好的示例指南,他运行了一个简单的小程序,打印了一条特定的消息,然后他使用一种我不再记得的方法更新了程序,突然间该程序用新的打印功能替换了旧的打印功能.

Through some magic interface it was apparently possible to declare some classes or functions replaceable during runtime.
I found a nice example guide of someone who ran a simple little program that printed a certain message, he then updated the program using a method I cannot remember anymore and all of a sudden the program had replaced that old print function with a new one.

我尝试通过 Java API 来激发我的记忆以及谷歌搜索,但没有成功.这里有人可以帮忙吗?

I've tried looking through the Java API to spark my memory as well as googling but without success. Can anyone here help?

推荐答案

各种应用容器都可以做到这一点.

Various app containers can do this.

基本上,您需要在新的 ClassLoader 中重新加载该类(除非您正在讨论在调试器下执行此操作,在这种情况下有完全不同的 API 可用).

Basically you'd need to reload the class in a new ClassLoader (unless you're talking about doing this under the debugger, in which case there are completely different APIs available).

在我看来,这种事情很少值得麻烦:设计一切以使其可以重新加载比将其设计为可以在新进程中完全重新启动要困难得多.如果流程中只加载了一个版本,则可以更轻松地确定正在运行的究竟是什么代码.

In my opinion, this kind of thing is rarely worth the hassle: designing everything so that it can be reloaded is considerably harder than designing it so it can be completely restarted in a new process. It's also easier to be sure exactly what code is running if there's only ever one version loaded in the process.

能够进行演示是一件很好的事情,但是对于大多数应用程序来说这是不值得的.在我看来,当然:)

It's a neat thing to be able to demo, but for most applications it's not worth it. All in my opinion, of course :)

请注意,一个显着的例外是无需重新启动容器即可重新加载 Web UI 层的能力:这可以让生活轻松.

Note that one notable exception is the ability to reload web UI layers without restarting the container: that can make life much easier.

这篇关于在运行时更新 Java 代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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