不,没有办法取消定义类并重新定义它。
最接近的方法是创建一个新的类加载器并使用它来加载该类的新版本。这就是“热加载”的实现方式。
然而,从 Java 运行时类型系统的角度来看,您实际上正在做的是创建一个新类型。(JLS 表示具有相同完全限定名称和不同类加载器的两个类是不同的类型。)
笔记:
同时拥有一个类型的多个版本可能会导致不直观的运行时类型错误。
You need to be careful about the relationship between the 2 class loaders. If the new one has the old one as a parent, things would get rather messed up.
This kind of thing can lead to some rather obscure memory leaks. While Class and ClassLoader objects can be garbage collected, there are some complex (hidden) dependencies between classloaders, classes and instances that mean that a single reachable instance can cause a classloader and all of its loaded classes remain reachable.
Why is there no way to do it?
原因之一是,它会严重破坏 JVM 的运行时类型安全性。考虑以下顺序。
加载以下类
public class Sneaky {
public long x = 42;
}
Run Code Online (Sandbox Code Playgroud)创建实例
Sneaky s = new Sneaky();
Run Code Online (Sandbox Code Playgroud)将类重新定义为新版本
public class Sneaky {
public String x;
}
Run Code Online (Sandbox Code Playgroud)尝试使用x我们之前创建的对象的字段。
System.out.println(s.x.length());
Run Code Online (Sandbox Code Playgroud)
将会发生非常糟糕的事情......
| 归档时间: |
|
| 查看次数: |
414 次 |
| 最近记录: |