[英]How to use a static variable from a class to update a non-static instance variable in another class?
[英]I need to use a non-static variable inside a static class… How to get around this?
以下是有关问题的概述:
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
}
}
}
我知道我无法从静态类中访问非静态变量,但是我无法使myCursor成为静态对象,因为它将需要将几乎所有函数更改为静态对象。 有小费吗?
为什么内部类是静态的? 如果删除静态修饰符,则它可以访问其封闭的类,然后可以访问myCursor。
如果必须是静态的,则可以将必需的Foo
对象传递到其构造函数中,并将其用作对封闭类的引用。 不那么整洁,但它仍然可以正常工作。
无论如何, static
(在字段上)表示它属于类而不是对象。 您可能对final
感到困惑,这意味着引用不能被修改?
在内部类上,它的行为有所不同(不一定是逻辑上的!),它从内部类中删除对外部类的引用,因此它本质上是一个完全独立的类,仅位于另一个类中。
如果您需要更详细的答案,则必须提供有关应用程序上下文的更多详细信息-仅凭该代码段很难说出什么应该是静态的,什么不应该是静态的。
几个选择
Foo
(或直接myCursor
)对象传递给MySurfaceView
构造函数。 MySurfaceView
非静态 如Java教程所述,静态嵌套类无权访问封闭类的其他成员,这使我想知道为什么您需要MySurfaceView类是静态的? 您可以将其设为嵌套类
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.