通过java中的setter和getter访问内部方法中的值



这似乎是一个简单的问题,但我的java知识有限。

考虑以下代码:

public void method1(){
Object1 obj = new Object1(){
@Override
public void innerMethod(Object response){
setList(response.list);
// Displaying the result of the getter is for sample purposes
System.out.println(getList().get(0).getName()); // This works and prints out the name of the first item.
}
};
obj.execute(); // Suppose execute method is pre-defined and just means it'll execute the `innerMethod`.
System.out.println(getList().get(0).getName()); // This returns null for the getList().
}

根据我对运行时执行的理解,一旦method1运行,就应该填充list,因为innerMethod是第一个写入的。

请帮助我理解为什么getList()的第二次访问返回null,以及我如何访问innerMethod的数据。

另外请注意,我在另一个类中使用getList(),它也返回null。

编辑:以下是上述场景的完整代码。

public void callMusicAPI(){
Callback<SongList> callback = new Callback<SongListResponse>(){
@Override
public void onResponse(Call<SongListResponse> call, Response<SongListResponse> response) {
setSongListResult(response.body().getResults());
Log.d(TAG, "Number of Songs received: " + Songs.size()); // This works.
Log.d(TAG, "Actual Response from API Call: " + response.raw() + "" + success + " " + getSongListResult().get(1).getTitle()+getSongListResult().get(1).getRelease_date() ); //This works.
}
@Override
public void onFailure(Call<SongListResponse> call, Throwable throwable) {
Log.e(TAG, throwable.toString());
}
};
call.enqueue(callback);
if(call.isExecuted()) {
if (getSongListResult() != null) {
Log.d(TAG, "Data received in setter and getter: " + getSongListResult().get(2).getTitle() + getSongListResult().get(2).getRelease_date()); 
} else {
Log.e(TAG, "List is super null");
}
}

}

public void setSongListResult(List<Song> songs){
this.songs = songs;
}
public List<Song> getSongListResult(){
return this.songs;
}

我预计call.enqueue(callback)之后会填充列表,但事实并非如此。

请注意,这是否是一个java问题,setter-getter在大多数情况下都可以正常工作,或者这是否特定于api调用的响应。如果,那么如果问题需要更改,请推荐。

实际上,我更愿意写一条评论,但由于我没有足够的声誉来做这件事,我会把我的输入作为答案。我希望我能帮上忙。

在我看来,范围好像有问题。如果您删除第二个getList()"无法访问"的所有代码,它看起来像这个

public void method1(){
Object1 obj = new Object1(){}
obj.execute(); // Suppose execute method is pre-defined and just means it'll execute the `innerMethod`.
System.out.println(getList().get(0).getName()); // This returns null for the getList().
}

getList()似乎什么都得不到,所以也许这就是你问题的原因。

public void method1(){
Object1 obj = new Object1(){
@Override
public void innerMethod(Object response){
setList(response.list);
// Displaying the result of the getter is for sample purposes
System.out.println(getList().get(0).getName()); // This works and prints out the name of the first item.
}
};
obj.execute(); // Suppose execute method is pre-defined and just means it'll execute the `innerMethod`.
System.out.println(obj.getList().get(0).getName()); // <-- ***********
}

我认为您调用getList((的对象不对。如果您没有指定要从中调用方法的对象,则假定为this.list((,在这种情况下,您将获得未初始化的数据成员。

最新更新