简体   繁体   English

在不指定实现接口的类的情况下调用接口方法

[英]Calling Interface Method Without Specifying The Class Implementing The Interface

I'd like to call an interface method so it executes in the class implementing that interface. 我想调用一个接口方法,以便它在实现该接口的类中执行。 I know I can create an object of that class to call the method, but is there a way to just make one call, then any class implementing the interface would execute the method? 我知道我可以创建该类的对象来调用该方法,但是有一种方法可以只进行一次调用,那么任何实现该接口的类都可以执行该方法? Just like protocols in iOS. 就像iOS中的协议一样。

For example I have this class for all Firebase operations, and after each operation I'd like to send a message of success to whatever class made the call. 例如,对于所有Firebase操作,我都有一个此类,在每个操作之后,我想向发出呼叫的任何类发送成功消息。

This is the interface class: 这是接口类:

      public interface MemberNoteSend {
          public void doneSendNote(String msg);
      }

This is one of the classes implementing the interface: 这是实现接口的类之一:

public class CoachFragment extends Fragment  implements MemberNoteSend {

This is a method in a class to handle Firebase operations: 这是类中用于处理Firebase操作的方法:

    public static void sendNoteToMember(String userKey, String note, String source){

    databaseRef.child(Constants.NODE_USERS)
               .child(userKey)
               .child(Constants.NODE_NOTES)
               .push()
               .setValue(noteObj).addOnCompleteListener(new OnCompleteListener<Void>() {
        @Override
        public void onComplete(@NonNull Task<Void> task) {
            CoachFragment cf = new CoachFragment(); // I DON'T WANT THIS OBJECT
            if(task.isSuccessful()) {
                cf.doneSendNote("Note sent");
            }else{
                cf.doneSendNote("Error");
            }
        }
    });
}

I don't want to make an object of CoachFragment class because this method can be called from more than one fragment of activity. 我不想创建CoachFragment类的对象,因为可以从多个活动片段中调用此方法。 I'm open to other ways to achieve this functionality. 我愿意采用其他方式来实现此功能。

after each operation I'd like to send a message of success to whatever class made the call. 每次操作后,我想向发出呼叫的任何类发送成功消息。

So it's not any . 因此,它不是任何 The proper way to do that (IMHO) is to use something like: 正确的方法(IMHO)是使用类似以下内容的方法:

public static void sendNoteToMember(final MemberNoteSend sender, String userKey, String note, String source) {
    // ...
    if (task.isSuccessful()) {
        sender.doneSendNote("Note sent");
        // ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM