简体   繁体   English

java在内部函数中调用父级的回调函数

[英]java call parent's callback function in inner function

platform: android 平台:Android

I'm new to java, I want to do something like this: 我是java的新手,我想做这样的事情:

private void PostToServer(final Callback mycallback){

    OkHttpClient client= new OkHttpClient();
    //some codes....
    client.newCall(req).enqueue(new Callback(){
       private void onFailure(Request req,IOException e){
           tip("SERVER ERROR!");
       }
       private void onResponse(Response resp){
          Call mycallback(resp); //how to call the callback?
       }
    }
}

I want to use it like this:(make a interface my own?) 我想这样使用它:(将接口设为我自己的?)

PostToServer(new callback(){
    @Override
    private void onSuccess(String resp){
      if(resp==1){
         tip("SERVER CONNECTED!");
      }
    }
});

GOAL: call mycallback in onResponse(). 目标:在onResponse()中调用mycallback。

btw what is this type of code called? 顺便说一句,这种类型的代码叫什么? what are the keywords should I use to search? 我应该使用哪些关键词进行搜索?

thanks so much! 非常感谢!

okhttp callback interface: direct link okhttp回调接口: 直接链接

package com.squareup.okhttp;    
import java.io.IOException;

public interface Callback {    
  void onFailure(Request request, IOException e);    
  void onResponse(Response response) throws IOException;
}

Not sure what the concrete question is. 不知道具体的问题是什么。 But you are using an anonymous inner class. 但是您正在使用匿名内部类。 And you can only access objects from the outside if they are final. 而且,只有最终对象才能从外部访问。 With Java 8 your callback parameter should be implicit final. 对于Java 8,您的回调参数应为隐式final。 If you are using Java 7 (which you are doing in case of Android IIRC) you need to mark your parameter with the final keyword. 如果您使用的是Java 7(在Android IIRC的情况下就是这样做的),则需要用final关键字标记参数。

If you are asking about the design pattern you are trying to achieve ... what you are doing is similar to functional programming, as you are passing the function that should be executed as callback object. 如果您正在询问要尝试实现的设计模式,您正在做的工作与函数式编程类似,因为您传递了应作为回调对象执行的函数。

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

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