不能对非静态方法进行静态引用 [英] Cannot make a static reference to the non-static method

查看:47
本文介绍了不能对非静态方法进行静态引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

用 Java 构建多语言应用程序.从 R.string 资源 XML 文件插入字符串值时出错:

Building a multi-language application in Java. Getting an error when inserting String value from R.string resource XML file:

public static final String TTT =  (String) getText(R.string.TTT);

这是错误信息:

错误:无法从类型中静态引用非静态方法 getText(int)上下文

Error: Cannot make a static reference to the non-static method getText(int) from the type Context

这是怎么引起的,我该如何解决?

How is this caused and how can I solve it?

推荐答案

由于 getText() 是非静态的,您不能从静态方法中调用它.

Since getText() is non-static you cannot call it from a static method.

要了解原因,您必须了解两者之间的区别.

To understand why, you have to understand the difference between the two.

实例(非静态)方法适用于特定类型(类)的对象.这些是用新创建的,如下所示:

Instance (non-static) methods work on objects that are of a particular type (the class). These are created with the new like this:

SomeClass myObject = new SomeClass();

要调用实例方法,请在实例 (myObject) 上调用它:

To call an instance method, you call it on the instance (myObject):

myObject.getText(...)

但是静态方法/字段可以直接在类型上调用,如下所示:前面的说法是不正确的.还可以使用像这样的对象引用来引用静态字段 myObject.staticMethod() 但不鼓励这样做,因为它没有明确说明它们是类变量.

However a static method/field can be called only on the type directly, say like this: The previous statement is not correct. One can also refer to static fields with an object reference like myObject.staticMethod() but this is discouraged because it does not make it clear that they are class variables.

... = SomeClass.final

并且两者不能一起工作,因为它们操作的是不同的数据空间(实例数据和类数据)

And the two cannot work together as they operate on different data spaces (instance data and class data)

让我试着解释一下.考虑这个类(伪代码):

Let me try and explain. Consider this class (psuedocode):

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";

价值是什么?

好吧

in item1 TTT = 1 and somedata = 200
in item2 TTT = 1 and somedata = 99

换言之,TTT 是该类型的所有实例共享的数据.所以说

In other words, TTT is a datum that is shared by all the instances of the type. So it make no sense to say

class Test {
         string somedata = "99";
         string getText() { return somedata; } 
  static string TTT = getText(); // error there is is no somedata at this point 
}

所以问题是为什么 TTT 是静态的,或者为什么 getText() 不是静态的?

So the question is why is TTT static or why is getText() not static?

删除 static 并且它应该可以克服这个错误 - 但是不了解您的类型是做什么的,它只是一个粘贴膏药直到下一个错误.getText() 有哪些要求它是非静态的?

Remove the static and it should get past this error - but without understanding what your type does it's only a sticking plaster till the next error. What are the requirements of getText() that require it to be non-static?

这篇关于不能对非静态方法进行静态引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆