内部类非最终变量java [英] inner class non-final variable java
问题描述
我需要更改内部类中的变量,并且我得到了臭名昭着的不能引用在不同方法中定义的内部类中的非final变量错误。
I needed to change variables inside an inner class and I got the infamous "Cannot refer to a non-final variable inside an inner class defined in a different method" error.
void onStart(){
bt.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
int q = i;
}
});
}
我很快就开了一个班,里面有我想改变的所有东西,在内部类之外制作了类的最终版本
I quickly made a class that held all of the things I wanted to change and made a final version of the class outside the inner class
class temp{
int q;
}
void onStart(){
final temp x = new temp();
bt.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
x.q = i;
}
});
}
这似乎是我需要的,它有效,但我想知道这是否是如何正确解决问题。另外,我真的很讨厌用 temp
这个词来命名我的班级。是否有一个实际的编程术语,以便我为我的班级创建一个更具描述性的名称?
This seems to be what I need and it works but I am wondering if this is how to correctly work around the problem. Also, I really hate using the word temp
to name my class. Is there an actual programming term for what I did so that I make a more descriptive name for my class?
推荐答案
你可以简单创建一个内部类而不是一个匿名的(就像你现在正在做的那样)。然后你有一个构造函数和你想要设置你的成员的任何其他方法。不需要任何hackiness(如1个案例的数组)。
You can simply create an inner class instead of an anonymous one (like you are currently doing). Then you have a constructor and any other methods you want to set your members. No hackiness required (like the array of 1 case).
如果班级要求与其外部类别进行任何数据交换,我会发现这个更干净,但承认这是个人偏好。 1个成语的数组也会起作用并且更简洁,但坦率地说,它看起来很难看。我通常将匿名内部类限制为仅执行操作而不尝试更新外部类中的数据的内部类。
I find this cleaner if the class requires any exchange of data with its outer class, but admit it is a personal preference. The array of 1 idiom will work as well and is more terse, but frankly, it just looks fugly. I typically limit anonymous inner classes to those that just perform actions without trying to update data in the outer class.
例如:
private MyListener listener = new MyListener();
void onStart(){
bt.setOnClickListener(listener);
}
class MyListener implements OnClickListener
{
String name;
int value;
void setName(String newName)
{
name = newName;
}
void setValue(int newValue)
{
value = newValue;
}
public void onClick(View v)
{
// Use the data for some unknown purpose
}
}
如果涉及多个线程,则还必须使用适当的同步。
If there are multiple threads involved, then appropriate synchronization will have to be used as well.
这篇关于内部类非最终变量java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!