[英]How can I transfer a variable from one method to another without storing it in a class in Java?
[英]How can I call the retrieved JSON object from one method to another without storing it as a string?
我已经从对Java类中一个方法的响应中检索了一个JSON对象。 现在,我想在同一类的另一个方法中使用同一对象。 我该怎么做?
假设您是Java的新手,传递参数的基本格式是使用=
赋值:
public void callerMethod() {
JsonObject myResponse = getResponse(); // call the method and put the response in the variable
doSomething(myResponse); // pass the variable to a method
}
private void doSomething(JsonObject myResponse) { // this method gets the variable from the call above
// do whatever you want with myResponse here
}
希望有帮助吗?
您可以通过多种方式实现所需的目标:
首先,您可以在类中创建一个字段,并在检索对象时实例化该字段。
然后,您可以在任何地方的课堂中使用它。 您甚至可以将其public
,也可以在其他类中使用它。
例如:
public class JsonReader{
public JsonObject object; //field in your class (still not instantiated)
public JsonReader(){
object = readMyJson(); //declare a readMyJson method to retrieve your object
...
}
//other methods
public someFunction(){
//here you have access to your object.
}
}
或者,您可以按照@Matt答案所示将局部变量传递给每个方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.