用 Java 构建多语言应用程序。从 R.string
资源 XML 文件插入字符串值时出现错误:
public static final String TTT = (String) getText(R.string.TTT);
这是错误消息:
Error: Cannot make a static reference to the non-static method getText(int) from the type Context
这是怎么造成的,如何解决?
最佳答案
由于 getText()
是非静态的,因此您无法从静态方法调用它。
要理解其中的原因,您必须了解两者之间的区别。
实例(非静态)方法适用于特定类型(类)的对象。这些是用 new 创建的,如下所示:
SomeClass myObject = new SomeClass();
要调用实例方法,请在实例 (myObject
) 上调用它:
myObject.getText(...)
但是静态方法/字段可以仅直接在类型上调用,如下所示:
之前的说法不正确。 One can also refer to static fields with an object reference like myObject.staticMethod()
但这是不鼓励的,因为它没有明确表明它们是类变量。
... = SomeClass.final
两者不能一起工作,因为它们操作不同的数据空间(实例数据和类数据)
让我尝试解释一下。考虑这个类(伪代码):
class Test {
string somedata = "99";
string getText() { return somedata; }
static string TTT = "0";
}
现在我有以下用例:
Test item1 = new Test();
item1.somedata = "200";
Test item2 = new Test();
Test.TTT = "1";
值(value)观是什么?
嗯
in item1 TTT = 1 and somedata = 200
in item2 TTT = 1 and somedata = 99
换句话说,TTT
是由该类型的所有实例共享的数据。所以说没有意义
class Test {
string somedata = "99";
string getText() { return somedata; }
static string TTT = getText(); // error there is is no somedata at this point
}
所以问题是为什么TTT是静态的或者为什么 getText() 不是静态的?
删除static
,它应该会克服这个错误 - 但如果不了解你的类型的作用,它只是一个橡皮膏,直到出现下一个错误。 getText()
要求它是非静态的有哪些要求?
关于java - 无法对非静态方法进行静态引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60191983/