Java 如何在完全不同的方法中使用局部方法变量?
我有一个这样写的方法Java 如何在完全不同的方法中使用局部方法变量?,java,android,methods,Java,Android,Methods,我有一个这样写的方法 public void getRequest(String Url) { runOnUiThread(new Runnable() { public void run() { // TODO Auto-generated method stub HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet(url);
public void getRequest(String Url) {
runOnUiThread(new Runnable() {
public void run() {
// TODO Auto-generated method stub
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
try {
HttpResponse response = client.execute(request);
Toast.makeText(MenuUtama.this, request(response) ,Toast.LENGTH_SHORT).show();
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
}
我需要能够用另一种方法访问局部变量
request
,以便调用request.response
。如何从完全不同的方法访问此局部方法?增加响应和请求变量的范围,我的意思是在类级别而不是在方法级别声明这些变量。您不能在任何函数中调用任何变量作为局部变量声明。您可以按如下方式进行操作
public class A{
HttpGet request;
HttpResponse response;
void methodA(){
request = //........
response = //...........
}
void methodB{
//here you can refer to request and response as they are the instance variables of the class.
}
}
A a = new A();
//now you can call a.request or a.response
如果要从类外部访问这些对象,则必须创建一个类A的对象,然后按如下方式调用
public class A{
HttpGet request;
HttpResponse response;
void methodA(){
request = //........
response = //...........
}
void methodB{
//here you can refer to request and response as they are the instance variables of the class.
}
}
A a = new A();
//now you can call a.request or a.response
但是请记住,变量访问说明符应该允许您这样做。我认为您需要的是以下几点:
protected Object myRequest;
public void getRequest(String Url) {
runOnUiThread(new Runnable() {
public void run() {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
try {
HttpResponse response = client.execute(request);
myRequest = request(response);
Toast.makeText(MenuUtama.this, myRequest, Toast.LENGTH_SHORT).show();
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
}
显然,将
Object
更改为request(response)
所定义的任何类,重命名myRequest
,并更倾向于在私有实例变量上使用访问器,而不是直接对其进行保护和赋值,但希望您能理解这一点,您需要一个实例变量来保存方法调用请求(响应)
的值,您应该在类级别的范围内声明响应
变量。这是你的密码
public class YourClass{
//Declare your request varible in a class-level scope
//so it can be accessed by any method
HttpGet request;
public void getRequest(String Url) {
runOnUiThread(new Runnable() {
public void run() {
// TODO Auto-generated method stub
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
try {
response = client.execute(request);
Toast.makeText(MenuUtama.this, request(response) ,Toast.LENGTH_SHORT).show();
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
}
public void otherMthod(){
System.out.println(request); //request variable is accessible in this scope.
}
}
请求(响应)如何成为变量???
request(响应)
在您的snip中,它不是变量。由于存在各种选项,您试图实现的是什么,但可能在线程安全等方面存在问题。正如aij和radimpe指出的,请求(响应)不是一个变量。无论如何,如果您想引用其他方法中的变量,那么您可以将该变量作为实例变量,就像在任何块之外的类中声明它一样?这将使您的应用程序在HTTP命令执行完毕之前无响应。你应该在一个完全独立的线程上运行它。代码提示OP希望在多线程环境中运行它。将请求之类的内容保存到类变量中不会导致问题吗?