简体   繁体   English

Java - 如何避免接口中的静态和默认方法

[英]Java - How to avoid static and default methods in interface

My question is rather theoretical: 我的问题相当理论化:

Lets say I have Java 8 project using static and default methods in interfaces. 让我们说我在接口中使用staticdefault方法的Java 8项目。 I need to get rid of them because I am porting the code to Java 7 (lets say it is an Android app prior to Android N). 我需要摆脱它们,因为我将代码移植到Java 7(假设它是Android N之前的Android应用程序)。

How to do that? 怎么做? I know there is Retrolambda plugin for that and I successfully use it. 我知道有Retrolambda插件 ,我成功使用它。 But I am thinking about "pure" solution done by altering the code. 但我正在考虑通过改变代码来完成“纯粹”的解决方案。 What are the options? 有什么选择?

I know I can remove static and default methods from interface and put them into abstract class that implements this interface and then alter the code wherever there is reference to that interface (this is what Retrolambda does, if I understood the process correctly). 我知道我可以从接口中删除静态和默认方法,并将它们放入实现此接口的抽象类中,然后在引用该接口的任何地方更改代码(如果我正确理解了该过程,这就是Retrolambda所做的)。

My teacher had indicated it can be done just by "suitable change in interface definition" without using additional class. 我的老师表示可以通过“适当更改界面定义”来完成,而无需使用额外的课程。 But so far I failed in finding the solution. 但到目前为止,我找不到解决方案。 I tried putting implementations directly into target classes but that caused a series of troubles in my particular project. 我尝试将实现直接放到目标类中,但这在我的特定项目中引起了一系列麻烦。

Anyone have some idea or clue I am missing? 任何人都有一些想法或线索我失踪了吗?

I think it is at first questionable that you actually used such a thing in your Java8 project. 我认为你在Java8项目中实际使用过这样的东西首先是个问题。 Interface should remain without implementations. 接口应保持不实现。 Default methods were introduced mainly for APIs backward compatibility(if method has to be added to Interface from previous versions and you can't afford to force users of API to change their code and you don't like creating InterfaceV2). 引入默认方法主要是为了向后兼容API(如果必须将方法添加到以前版本的Interface中,并且您不能强制API的用户更改其代码而您不喜欢创建InterfaceV2)。 Not for "daily usage". 不适用于“日常使用”。

I think when porting, you should just export the methods to the static *Util classes. 我认为在移植时,您应该将方法导出到static * Util类。 This way you can reuse it and you are not breaking the main principle of Interface. 通过这种方式,您可以重复使用它,而不是破坏Interface的主要原则。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM