有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java为什么实现了两个方法的TextWatcher inheritor和作为一个匿名类方法实现的第三个方法不能转换为lambda?

我有一个abstract class实现TextWatcher,在只需要afterTextChanged(Editable s)方法的情况下缩短代码

这门课看起来像这样

public abstract class AfterTextChangedTextWatcher implements TextWatcher {
    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }
}

问题是,为什么当我创建这个类的匿名实现时,afterTextChanged(Editable s)的调用不能转换为lambda(我使用retrolambda库)?有什么变通方法或模式可以将其转换为lambda吗

现在这个类的用法如下所示

currentPasswordInput.addTextChangedListener(new AfterTextChangedTextWatcher() {
            @Override
            public void afterTextChanged(Editable s) {
                presenter.queryCurrentPw(s.toString());
            }
        });

UPD:感谢tamtom的伟大answer

我将把我的新代码放在这里,它可以很好地总结一切

所以现在我的后文本更改侦听器变成了一个功能接口

@FunctionalInterface//this annotation ensures you, that the class has only 
//one unimplemented method. Otherwise, the program won't compile.
public interface AfterTextChangedTextWatcher extends TextWatcher {
@Override
default public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    // default keyword in method specifier allows you to add basic implementation right in the interface. In my case, this code should do nothing.
}

@Override
default public void onTextChanged(CharSequence s, int start, int before, int count) {

    //now we have two methods of TextWatcher interface implemented by 
    //default. The only afterTextChange remains abstract. This allows us to 
    //consider our AfterTextChangeListener interface as abstract
}

}

现在,我们的EditText字段已经准备好作为lambda获取AfterTextChangeTextWatcher。我们只需要将TextWatcher类型指定为AfterTextChangedTextWatcher

currentPasswordInput.addTextChangedListener((AfterTextChangedTextWatcher) s -> presenter.queryCurrentPw(s.toString()));

共 (1) 个答案

  1. # 1 楼答案

    A functional interface is an interface that has just one abstract method, and thus represents a single function contract.

    lambda需要这些功能接口,因此仅限于它们的单一方法。匿名接口仍然需要用于实现多方法接口

    addMouseListener(new MouseAdapter() {
    
        @Override
        public void mouseReleased(MouseEvent e) {
           ...
        }
    
        @Override
        public void mousePressed(MouseEvent e) {
          ...
        }
    

    如果您使用的是Java 8 通过使用助手接口,可以将多方法接口用于lambdas。这适用于这样的侦听器接口,其中不需要的方法的实现非常简单(即,我们也可以做MouseAdapter提供的):

    interface AfterTextChangedTextWatcher extends TextWatcher
    {
        @Override
        public default void beforeTextChanged(CharSequence s, int start, int count, int after) {}
    
    
        @Override
        public default void onTextChanged(CharSequence s, int start, int before, int count) {}
    
    }