如何在lambda中返回值

问题描述 投票:-2回答:1

我是java 8和lambda的新手,我不知道如何在lambda中返回值。我尝试了这段代码,但返回了null值,但在日志中记录了令牌。我也试过静态值,但它没有用。我想在另一个java类中返回此值并使用它。

 public  String GetToken(Context context,String user_name,String password) throws JSONException {
        RequestQueue requestQueue= Volley.newRequestQueue(context);
        JSONObject jsonBody = new JSONObject();
        jsonBody.put("user_name", user_name);
        jsonBody.put("password", password);
        final String mRequestBody = jsonBody.toString();

        StringRequest request = new StringRequest(
                    Request.Method.POST,
                    url,
                    response -> {
                        try {
                            JSONObject jso = new JSONObject(response);
                            String token=jso.getString("token");
                            result=token;
                        } catch (JSONException e) {
                            e.printStackTrace();
                            Log.i("GetTokene",e.toString());
                            result=e.toString();
                        }
                    },
                    error -> {
                        Log.i("GetTokenE",error.toString());
                         result=error.toString();
                    }
            ) {
                @Override
                public String getBodyContentType() {
                    return "application/json";
                }
                @Override
                public byte[] getBody() {
                    try {
                        return mRequestBody == null ? null : mRequestBody.getBytes("utf-8");
                    } catch (UnsupportedEncodingException uee) {
                        // VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", mRequestBody, "utf-8");
                        return null;
                    }
                }              
            };

            requestQueue.add(request);
            return result;
        }
java android lambda
1个回答
0
投票

仅仅因为使用lambda而不是匿名类,它仍然是一个回调函数,并且它仍将被异步调用。这意味着它无法向调用代码返回值,因为它将在以后的某个时间调用。您必须将需要结果的所有代码直接放入lambda,或者从那里调用它。

© www.soinside.com 2019 - 2024. All rights reserved.