我正在创建Android应用程序。我创建了一种方法testMethod1()
,然后创建了另一种方法testMethod2()
。我已经在testMethod1()
中声明了类的对象。如何访问testMethod2()
中的对象obj
?
Public class TestClass() {
public void testMethod1() {
final ModalClass obj = new ModalClass();
testMethod2();
}
public void testMethod2() {
//I want to access 'obj' here
}
}
编辑Quetion
我为ListView创建了模式。我想将数据设置为bellow的列表视图。但是我无法将locationDet
访问到另一种方法中。它显示can not resolve symbol 'locationDet'
。
Public class TestClass() {
private List<LocationDetailModel> LocationDetailList = new
ArrayList<LocationDetailModel>();
public void testMethod1() {
JSONArray results = response.getJSONArray("results");
for (int i = 0; i < results.length(); i++) {
final LocationDetailModel locationDet = new LocationDetailModel();
locationDet.setTitle(obj.getString("name"));
testMethod2();
LocationDetailList.add(locationDet);
}
}
public void testMethod2() {
//I want to access 'obj' here
locationDet.setRating(results.getInt("rating"));
}
}
您有两个选择:1.您将变量逃亡类称为以下:
Public class TestClass(){
final ModalClass var = new ModalClass();
public void testMethod1() {
var = new ModalClass();
testMethod2();
}
public void testMethod2() {
//I want to access 'var' here
}
}
否则您将var进行测试methode2这样:
Public class TestClass()
{
public void testMethod1() {
final ModalClass var = new ModalClass();
testMethod2(var);
}
public void testMethod2(ModalClass var) {
//I want to access 'var' here
}
}
您可以将ModalClass var
作为私人属性:
Public class TestClass(){
private final ModalClass var;
public void testMethod1() {
this.var = new ModalClass();
testMethod2();
}
public void testMethod2() {
//I want to access 'var' here
}
}
您可以访问范围且可见的变量。在您的情况下,您希望在另一种方法中使用local
变量。
-
您可以将其作为方法参数传递。为此,您需要修改如下
的方法的签名public void testMethod2( LocationDetailModel locationModelDet ){ // now you acess the locationModelDet }
您可以将locationDet
作为参数传递给testMethod2
作为testMethod(locationDet)
-
另一个替代选项是而不是使用本地变量,您可以创建一个实例变量为
private LocationDetailModel locationDet = new LocationDetailModel();
现在,在testMethod1()
中,您不需要创建本地变量,您只需设置title
即可。为此,您无需修改testMethid2()
的签名。您将能够在两种方法中都可以添加locationDet
。