簡體   English   中英

從封閉類中調用嵌套接口的方法

[英]call a method of nested interface from enclosing class

讓我們假設我有一個類,其在OuterClass有一個方法類方法()和嵌套接口NastedInterface這反過來有一個方法回調()。 那么如何在類classMethod()的方法中調用接口callback()的方法呢?

我的目標是能夠實現OuterClass.NastedInterface其他類和回調()方法,當類方法()將要在OuterClass稱為將被稱為做一些操作。 代碼看起來像這樣。

public class OuterClass {
    public void classMethod(){
        if(SOME_CONDITION){
            \\ here I want to call the **callback()** method of **NastedInterface**
        } 
    }

    public interface NastedInterface {
        void callback();
    }
}

實現該接口的類應該看起來像這樣。

public class TestClass implements OuterClass.NastedInterface {
    @Override
    public void callback (){
        DO SOMETHING....
    }
}

基本上,我想創建一個回調機制,例如我在Android中使用過很多次。 例如View.OnClickListener或所有其他此類的ON_SOMETHINK_LISTENER。

可能是我走錯了方向,需要以其他方式創建這種機制嗎?

將一個成員變量在您OuterClass持有的實例NestedInterface 添加一個設置該變量的setter方法,並將其公開。

在調用callback之前,請確保檢查成員是否為null。

為此,外部類需要引用TestClass。

所以:

public class OuterClass {

    private NastedInterface interfaceToCall;

    public void classMethod(){
        if(SOME_CONDITION){
            \\ here I want to call the **callback()** method of **NastedInterface**
            if(interfaceToCall != null)
            {
               interfaceToCall.callback();
            }
        } 
    }

    public interface NastedInterface {
        void callback();
    }
}

感謝大家的回答,我解決了這個問題,這里的每個答案都以某種方式對我有所幫助。 但是由於解決方案並不完全是答案中所建議的方式,因此我將在此處為將來可能需要的人編寫。

public class OuterClass {
    private NastedInterface nastedInterface;

    //In the constructor I am assigning the reference of the parent class 
    // of some other classes in my app which all may need to be notified when 
    // **callback()** has happened
    public OuterClass(){
        nastedInterface = TestClassParent.getInstance;
    }

    public void classMethod(){
        if(nastedInterface != null){
            nastedInterface.callback();
        } 
    }

    public interface NastedInterface {
        void callback();
    }
}

因此,這里有一個將成為其他一些類的父類的類,並將實現NastedInterface。

public class TestClassParent implements OuterClass.NastedInterface {
    private static TestClassParent instance;

    public static TestClassParent getInstance(){
        if(instance == null){
              instance = new TestClassParent();
         }

        return instance;
    } 

 @Override
 public void callback(){
     //I will override it in subclasses and do what I need in each class
 }
}

之后,我可以在擴展TestClassParent的任何類中接收callback()事件。 例如:

public class TestClass1 extends TestClassParent {

    @Override
    public void callback (){
        DO SOMETHING....
    }
}

public class TestClass2 extends TestClassParent {

    @Override
    public void callback (){
        DO SOMETHING ELSE....
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM