开发者

Does removing an interface break code calling methods on the object?

I need to do some refactoring in Java, and I need to maintain some degree of binary compatibility. In this case I want to remove some legacy interfaces, that are not used anywhere anymore and whi开发者_运维问答ch require a rather big (and also deprecated) external dependency.

I have class C that implements interface I, and I have code that calls a method (declared in the interface) on an instance of C. The calling code knows that it is using C, not just the interface.

 class C implements I {
      void theMethod(){} ; // is declared in the interface I
 }

 C object;
 object.theMethod();

When I remove the interface from the class definition (but keep all the methods), will the calling code (which does not refer to the interface at all) still work (without a recompile)?


Yes, it will work - as long as it doesn't explicitly refer to interface I anywhere.

From JLS: Resolution of Symbolic References:

The binary representation of a class or interface references other classes and interfaces and their fields, methods, and constructors symbolically, using the binary names (§13.1) of the other classes and interfaces

Class ClientClass referring to field / method of class C contains no implicit references to interface I that class may implement.


It works as long as an object of class C is never referred to as I.

You can also refer to Evolving Java-based APIs part 2.


You might have a problem with the calling Code if it imports the Interface anywhere. If there is no import of the interface in any of the calling code, you can be reasonably confident that your refactoring will work as planned.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜