最终局部变量可能没有在匿名内部类中初始化 [英] Final Local Variable may not have been initialized in anonymous inner class

查看:188
本文介绍了最终局部变量可能没有在匿名内部类中初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码:

final Foo myFoo = new Foo(new Inner() {
    @Override
    callback(){
         myFoo.bar();
    }
});

(含实际函数名)

final MyArrayAdapter aa = new MyArrayAdapter(new View.OnClickListener() {
    @Override
    onClick(){
         aa.notifyDataSetChanged();
    }
});

Java给我一个关于myFoo可能未被初始化的错误。有什么办法解决这个问题吗?我可以设置回调为null当我构造对象,然后改变它,但我希望有一个更清洁的方法。有任何想法吗? (如果Foo不是由我写的,并且没有公开一个接口来改变回调函数,这也不会工作)

Java is giving me an error about how myFoo might not have been initialized. Is there any way to fix this? I can potentially set the callback to null when I construct the object and then change it afterwards, but I'd hope for there to be a cleaner way. Any ideas? (Also that wouldn't work if Foo wasn't written by me and didn't expose an interface to change the callback later)

如果有人好奇,我的具体场景,Foo是一个ArrayAdapter,并且条形图是notifyDataSetChanged()。适配器显示的内容取决于数组中项目的值,这些值在单击时会更改。回调是clickListener。

In case anyone is curious, in my specific scenario, Foo is an ArrayAdapter, and the bar is notifyDataSetChanged(). What is displayed by the adapter depends on the values of the items in the array, and those values change when they are clicked on. The callback is the clickListener.

推荐答案

简单的答案是,你绝对不能在Java中做,你那个。你试图创建两个对象一次相互引用,这是一个鸡和鸡蛋的问题。

Short answer is that you definitely can't do that in Java, but the compiler already told you that. You're trying to create two objects at once with references to each other, it's a chicken and egg problem. Bottom line, you have to create ONE of them first.

建议是两个步骤的创建:

A suggestion is a two step creation:

....
final MyArrayAdapter aa = new MyArrayAdapter();
aa.initializeButtonClickListener();
....

,然后向适配器添加'initialize' / p>

and then add the 'initialize' method to the adapter.

public void initializeButtonClickListener(){
    this.button.setOnClickListener(new View.OnClickListener() {
        @Override
        onClick(){
             notifyDataSetChanged();
        }
    });
}

因为这种构造有点复杂(即,比简单调用构造函数),我建议然后将这两行引入 MyArrayAdapter 工厂方法,并将构造函数设为私有。

Because that construction is somewhat complicated (ie, more complicated than simply calling a constructor), I'd recommend then pulling those two lines in to a MyArrayAdapter factory method, and making the constructor private.

这篇关于最终局部变量可能没有在匿名内部类中初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆