我如何更改另一个 class 的变量?
How do i change a variable of another class?
我在 class "MainActivity" 中有一个名为 modeNr 的变量,它受到保护,因此应该可以从包内访问它,但是每当我尝试从 class 在同一个包中它给出了错误:"Non-static field 'modeNr' cannot be referenced from a static context"。我使用以下行来更改变量:
MainActivity.modeNr = 1;
关于问题是什么以及如何纠正它有什么想法吗?
您正在尝试从静态函数更改非静态成员。您还需要将该变量设为静态,或者需要创建该 class 的对象。
让我们假设,
class Test {
int node = 0;
static int node1 =10;
}
class changeNode {
public static void changeNode(){
new Test().node = somevalue;
//or you need to make node static and change like this
Test.node1 = some value
}
}
抱歉,我无法发表评论。
您的 modeNr 不是静态变量。您需要像这样定义它:
protected static String modeNr="ddddd"
因为你是MainActivity.modeNr修改的,所以这个变量必须是静态变量
要消除该错误,您需要将变量定义为静态变量。
static String modeNr="soemthing"
要访问静态变量,可以通过静态成员访问它,也可以通过对象访问它。
只需将 modeNr
设为变量 static
。
而且我认为日志 Non-static field 'modeNr' cannot be referenced from a static context
解释了一切。
我在 class "MainActivity" 中有一个名为 modeNr 的变量,它受到保护,因此应该可以从包内访问它,但是每当我尝试从 class 在同一个包中它给出了错误:"Non-static field 'modeNr' cannot be referenced from a static context"。我使用以下行来更改变量:
MainActivity.modeNr = 1;
关于问题是什么以及如何纠正它有什么想法吗?
您正在尝试从静态函数更改非静态成员。您还需要将该变量设为静态,或者需要创建该 class 的对象。 让我们假设,
class Test {
int node = 0;
static int node1 =10;
}
class changeNode {
public static void changeNode(){
new Test().node = somevalue;
//or you need to make node static and change like this
Test.node1 = some value
}
}
抱歉,我无法发表评论。
您的 modeNr 不是静态变量。您需要像这样定义它:
protected static String modeNr="ddddd"
因为你是MainActivity.modeNr修改的,所以这个变量必须是静态变量
要消除该错误,您需要将变量定义为静态变量。
static String modeNr="soemthing"
要访问静态变量,可以通过静态成员访问它,也可以通过对象访问它。
只需将 modeNr
设为变量 static
。
而且我认为日志 Non-static field 'modeNr' cannot be referenced from a static context
解释了一切。