[英]Default Method in Interface - Java
import java.util.List;
public interface IEntityParam {
public void validateParam(Object object);
public default void validateParam(Object object,List<String> Str){
validateParam(object);
}
}
Suppose IEntityParam
is very old interface extended by many classes and I need new method in it. 假设
IEntityParam
是很多类扩展的非常旧的接口,我需要新的方法。 I have added a new method in with another parameter. 我在另一个参数中添加了一个新方法。 But my default implementation doesn't use new parameter List in its default method.
但我的默认实现不会在其默认方法中使用新参数List。 Technically, there is no problem.
从技术上讲,没有问题。 But is it correct use of default method?
但它是否正确使用默认方法? Or Should I keep this new method to specific class as I am not using second parameter in default implementation.
或者我应该将此新方法保留到特定类,因为我在默认实现中没有使用第二个参数。
Note : The list of String which is supplied here is used in just one implementation right now but can be used in other implementation in future. 注意:此处提供的String列表现在仅用于一个实现,但将来可用于其他实现。 It is not very specific and can be used by other implementation as well.
它不是非常具体,也可以被其他实现使用。
This is probably a misuse of default methods. 这可能是对默认方法的误用。 Default methods are known to facilitate backward compatibility when interfaces/contracts evolve with new methods, but the problem in your case is that not all
IEntityParam
implementations care about the new version of the "contract". 当接口/契约随新方法发展时,已知默认方法有助于向后兼容,但在您的情况下,问题是并非所有
IEntityParam
实现都关心新版本的“契约”。 Default methods are conceptually part of the interface's contract. 默认方法在概念上是接口合同的一部分。
The normal way to address your current need is to extend the interface: 解决当前需求的常用方法是扩展接口:
public interface IEntityParam {
public void validateParam(Object object);
}
public interface IEntityParamExtended extends IEntityParam {
public default void validateParam(Object object,List<String> Str);
}
This way, your class that needs the second method will implement IEntityParamExtended
and provide an implementation for both methods; 这样,需要第二种方法的类将实现
IEntityParamExtended
并为这两种方法提供实现; while all other implemnetations of IEntityParam
remain unaffected. 而
IEntityParam
所有其他IEntityParam
仍然不受影响。
In the future, when IEntityParamExtended
needs to be promoted to IEntityParam
(ie, when the new method forms part of the IEntityParam
contract), you can use a default
method to avoid forcing all existing implementations to be changed and recompiled. 将来,当
IEntityParamExtended
需要提升为IEntityParam
(即,当新方法构成IEntityParam
合约的一部分时),您可以使用default
方法来避免强制更改和重新编译所有现有实现。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.