Java中的重构方法和二进制兼容性 [英] Refactored methods and binary compatibility in Java

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

问题描述

在重构方法时,很容易在Java中引入二进制不可编码(使用以前版本的代码)。

When refactoring methods it is easy to introduce binary incompabilities (with previous versions of the code) in Java.

考虑更改方法以将其参数的类型扩展为父接口:

Consider changing a method to widen the type of its parameter to a parent interface:

 void doSomething(String x);

 // change it to

 void doSomething(CharSequence c);

使用此方法的所有代码将继续编译而不进行更改,但它确实需要重新编译编译(因为旧的二进制文件将因MethodNotFoundError而失败)。

All the code that uses this method will continue to compile without changes, but it does require a re-compile (because the old binaries will fail with a MethodNotFoundError).

如何将方法拉入父类。这需要重新编译吗?

How about pulling a method up into a parent class. Will this require a re-compile?

// before
public class B extends A{
    protected void x(){};
}

// after
public class A {
    public void x(){};
}
public class B extends A{}

该方法已被移动从B到父A。它还改变了从受保护到公共的可见性(但这不是问题)。

The method has been moved from B to the parent A. It has also changed visibility from protected to public (but that is not a problem).

我是否需要维护二进制兼容性包装器 在B中,还是会继续工作(自动发送到父类)?

Do I need to maintain a "binary compatibility wrapper" in B, or will it continue to work (automatically dispatch to the parent class)?

 // do I need this ?
 public class B extends A{
     // binary compatibility wrapper
     public void x(){ super.x(); }
 }


推荐答案

拓宽会影响方法的签名,以便不是二进制兼容的。将方法移动到超类不会影响方法签名,因此它将起作用。 Eclipse有一个描述API和ABI兼容性的优秀文档:

"Widening" affects the signature of the method so that is not binary compatible. Moving a method to a superclass does not affect the method signature, so it will work. Eclipse has a great document that describes API and ABI compatibility:

http://wiki.eclipse.org/Evolving_Java-based_APIs

第2部分中有更明确的规则:

More explicit rules are in part 2:

http://wiki.eclipse.org/Evolving_Java-based_APIs_2

我相信你对改变形式参数的类型(即你所谓的扩展)或移动API方法向上类型层次结构感兴趣(即,你所谓的拉入父类)。

I believe you're interested in "Change type of a formal parameter" (i.e., what you refer to as widening) or "Move API method up type hierarchy" (i.e., what you refer to as pull into a parent class).

这篇关于Java中的重构方法和二进制兼容性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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