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

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

问题描述

在Java中构建多语言应用程序。从 R.string 资源XML文件插入String值时出错:

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(...)

但是,静态方法/字段可以直接称为,例如: s>
上一条语句不正确。 也可以引用带有对象引用的静态字段,例如 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";
}



现在我有以下用例:

Now I have the following use case:

Test item1 = new Test();
 item1.somedata = "200";

 Test item2 = new Test();

 Test.TTT = "1";

这些值是什么?

Well

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 
}

问题是为什么是 static或为什么是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天全站免登陆