[英]I need to use a non-static variable inside a static class… How to get around this?
Here's kind of an outline of the relevant problem: 以下是有关问题的概述:
public class Foo extends Activity{
Cursor myCursor;
public void onCreate(Bundle savedInstanceState) {
//I initialize myCursor here
}
public void setCursor(){
//When we are interested in a different set of data, the cursor changes here
}
public static class MySurfaceView extends SurfaceView implements Runnable{
public void run(){
//I need to access myCursor here
}
}
}
I know I cannot access a non-static variable from within a static class, but I can't make myCursor static because it would require changing almost all of my functions to static. 我知道我无法从静态类中访问非静态变量,但是我无法使myCursor成为静态对象,因为它将需要将几乎所有函数更改为静态对象。 Any tips?
有小费吗?
Why is the inner class static? 为什么内部类是静态的? If you remove the static modifier then it will have access to its enclosing class and subsequently to myCursor.
如果删除静态修饰符,则它可以访问其封闭的类,然后可以访问myCursor。
If it has to be static then you could just pass in the necessary Foo
object into its constructor and use that as your reference to the enclosing class. 如果必须是静态的,则可以将必需的
Foo
对象传递到其构造函数中,并将其用作对封闭类的引用。 Not as neat but it should still work. 不那么整洁,但它仍然可以正常工作。
Regardless, static
(on a field) means it belongs to the class not the object. 无论如何,
static
(在字段上)表示它属于类而不是对象。 You may be getting confused with final
which means the reference can't be modified? 您可能对
final
感到困惑,这意味着引用不能被修改?
On an inner class, it behaves differently (and not necessarily logically!) It removes the reference from the inner class to the outer class, so it's essentially a completely separate class just sitting within another. 在内部类上,它的行为有所不同(不一定是逻辑上的!),它从内部类中删除对外部类的引用,因此它本质上是一个完全独立的类,仅位于另一个类中。
If you want a more detailed answer, you'll have to provide more details about the context of your applciation - it's difficult to say what should and shouldn't be static just from that code snippet. 如果您需要更详细的答案,则必须提供有关应用程序上下文的更多详细信息-仅凭该代码段很难说出什么应该是静态的,什么不应该是静态的。
Couple of choices 几个选择
Foo
( or directly myCursor
) object to MySurfaceView
constructor. Foo
(或直接myCursor
)对象传递给MySurfaceView
构造函数。 MySurfaceView
non-static MySurfaceView
非静态 Static nested classes do not have access to other members of the enclosing class, as stated in the java tutorials , which makes me wonder why do you need MySurfaceView class to be static? 如Java教程所述,静态嵌套类无权访问封闭类的其他成员,这使我想知道为什么您需要MySurfaceView类是静态的? You can just make it a nested class
您可以将其设为嵌套类
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.