[英]Why TextWatcher inheritor with two methods implemented, and third implemented as anonimous class method can't be converted to lambda?
我有一個實現TextWatcher
的abstract class
,以在僅需要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());
}
});
我將把可以很好地總結所有內容的新代碼放在這里。
所以現在我的AfterTextChangeListener變成了FunctionalInterface。
@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字段已准備就緒,可以將AfterTextChangeTextWatcher作為lambda獲取。 我們所需要做的就是將TextWatcher類型指定為AfterTextChangedTextWatcher。
currentPasswordInput.addTextChangedListener((AfterTextChangedTextWatcher) s -> presenter.queryCurrentPw(s.toString()));
功能接口是僅具有一種抽象方法的接口,因此表示單個功能協定。
Lambda需要這些功能接口,因此僅限於它們的單一方法。 仍然需要使用匿名接口來實現多方法接口。
addMouseListener(new MouseAdapter() {
@Override
public void mouseReleased(MouseEvent e) {
...
}
@Override
public void mousePressed(MouseEvent e) {
...
}
如果您使用的是Java 8,則可以通過使用輔助程序接口將多方法接口與lambda結合使用。 這可與此類偵聽器接口一起使用,在這些偵聽器接口中,不需要的方法的實現是微不足道的(即,我們也可以執行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) {}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.