2013-12-23 29 views
2

的方法讓我們假設我有一個類在OuterClass其中有一個方法類方法()和嵌套接口NastedInterface這反過來有一個方法回調()。那麼我怎樣才能調用接口的方法classMethod()?回調()調用嵌套接口從封閉

我的目標是能夠實現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。

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

+0

我刪除了自己的Android標籤,因爲這是java的問題。 – cbrulak

+0

您需要對實現類實例的引用來調用該方法。 –

+0

Ops。對不起)我真的需要這個機器人,但是,是的,你是對的 - 這是完全的JAVA問題。 – Andranik

回答

2

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

確保在致電callback之前檢查成員是否爲空。

1

Outerclass需要對此工作的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(); 
    } 
} 
0

感謝大家的回答,我解決了這個問題,每個答案都以某種方式幫助了我。但是,由於解決方案並不完全如何在答案中提出建議,我會在此爲未來需要的人寫信。

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任何班上回調()事件。例如:

public class TestClass1 extends TestClassParent { 

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

public class TestClass2 extends TestClassParent { 

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