如何从Java接口中获取值
我在接口方法中有一个变量,并且我希望它在接口之外:
String responseString;
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
// i want this value out!
responseString = response.toString();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
System.out.println(error.toString());
}
});
当然,我不能只分配wenderseString = wendesp.tostring()
,因为它们具有不同的范围。那我该怎么做呢?
大概这个问题已经回答,但我在网上找不到类似的东西。
I have a variable inside an interface method and I want it outside the interface:
String responseString;
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
// i want this value out!
responseString = response.toString();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
System.out.println(error.toString());
}
});
Of course I can't just assign responseString = response.toString()
because they have different scopes. So how can I do this?
Probably this question has already been answered but I couldn't find anything similar online.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
根据JSON结构或JSONOBJECT尝试一次。
Try this once as per your JSON structure Either JSONArray or JSONObject.
新响应。listener&lt; string&gt;(){...}
所使用的方法称为“匿名”实现。确实,您正在实现接口,但是您在代码中没有对其进行任何静态引用。您应该做的是,要实现正常实现界面,哪些界面当然会实现所需的方法,还可以容纳一个领域和特殊的领域:
现在,您应该能够做到这一点:
当然,请小心你是一个听众。该值将为
null
,直到方法OnResponse
将其同步回电为止。The
new Response.Listener<String>() {...}
that you're doing in that method is called "anonymous" implementation. Indeed you are implementing the interface, but you don't hold any static reference to it in the code.What you should do, is to have a normal implementation of the interface which of course implements the method required, but also holds a field and a special getter for your field:
Now, you should be able to do this:
Of course, be careful you're into a listener. The value will be
null
until when the methodonResponse
will have asynchronously been called back.