从封闭类调用嵌套接口的方法

时间:2013-12-23 19:58:07

标签: java callback

假设我有一个类 OuterClass ,它有一个方法 classMethod()和一个嵌套的接口 NastedInterface ,它又有一个方法的回调()即可。那么如何在类 classMethod()的方法中调用接口 callback()的方法?

我的目标是能够在其他类中实现 OuterClass.NastedInterface ,并在 callback()方法中执行一些操作,这将在 classMethod()将在 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。

可能是我走向了错误的方向,我需要以其他方式创建这样的机制?

3 个答案:

答案 0 :(得分:2)

OuterClass中放置一个包含NestedInterface实例的成员变量。添加一个设置该变量的setter方法,并将其公开。

在调用callback之前,请确保检查该成员是否为空。

答案 1 :(得分: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();
    }
}

答案 2 :(得分: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 的类中接收 callback()事件。例如:

public class TestClass1 extends TestClassParent {

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

public class TestClass2 extends TestClassParent {

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