java 不能在静态上下文中使用“this”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17233367/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Cannot use 'this' in static context
提问by Mike Baxter
My aim is to have a class containing all functions which perform database operations cleanly and neatly - which can also be called with a single line of code, eg; DbFunctions.AddContact("fName", "lName");
我的目标是拥有一个包含所有函数的类,这些函数可以干净利落地执行数据库操作——也可以用一行代码调用,例如; DbFunctions.AddContact("fName", "lName");
I have a DBAdapter class which I have read in a tutorial:
我有一个 DBAdapter 类,我在教程中读过它:
public class DBAdapter {
static final String KEY_ROWID = "_id";
static final String KEY_NAME = "name";
static final String KEY_EMAIL = "email";
static final String TAG = "DBAdapter";
static final String DATABASE_NAME = "MyDB";
static final String DATABASE_TABLE = "contacts";
static final int DATABASE_VERSION = 1;
static final String DATABASE_CREATE =
"create table contacts (_id integer primary key autoincrement, "
+ "name text not null, email text not null);";
final Context context;
DatabaseHelper DBHelper;
SQLiteDatabase db;
public DBAdapter(Context ctx)
{
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
private static class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db)
{
try
{
db.execSQL(DATABASE_CREATE);
}
catch (SQLException ex)
{
ex.printStackTrace();
}
}
}
//---opens the database---
public DBAdapter open() throws SQLException
{
db = DBHelper.getWritableDatabase();
return this;
}
//---closes the database---
public void close()
{
DBHelper.close();
}
// some other database functions here... inserts, updates etc
}
And I have created my own class to handle all calls to the DBAdapter:
我创建了自己的类来处理对 DBAdapter 的所有调用:
public static class DatabasesActivity extends Activity
{
static DBAdapter db;
// Called when activity is first created
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public static long addContact(String name, String email)
{
if (db == null) {
db = new DBAdapter(this); // <--- compiler error here
}
db.open();
long id = db.insertContact("Joe Bloggs", "[email protected]");
db.close();
return id;
}
}
In the addContact
method, on the line: db = new DBAdapter(this);
, I get the following error: Cannot use 'this' in a static context
.
在addContact
方法中,就行:db = new DBAdapter(this);
,我收到以下错误:Cannot use 'this' in a static context
。
I am familiar with OOP concepts so I understand whyI am getting this error - but being new to java itself, I am looking for alternate methods on what I'm trying to achieve. The DBAdapter class constructor takes in a context
parameter, but I am unsure why as I have not written that class myself.
我熟悉 OOP 概念,所以我明白为什么我会收到这个错误 - 但我是 java 本身的新手,我正在寻找我想要实现的替代方法。DBAdapter 类构造函数接受一个context
参数,但我不确定为什么,因为我没有自己编写该类。
To Clarify:
I understand why the error is occurring. The DBAdapter class constructor takes in a context
parameter, and I don't know what to pass in as the context parameter when I'm using it statically. I want the class to be static as I don't want to have to instantiate it every time I want to use it.
澄清:我明白为什么会发生错误。DBAdapter 类构造函数接受一个context
参数,我在静态使用它时不知道将什么作为上下文参数传入。我希望该类是静态的,因为我不想每次使用它时都必须实例化它。
I guess my real question would be "why does SQLiteOpenHelper require a context?"
我想我真正的问题是“为什么 SQLiteOpenHelper 需要上下文?”
回答by NINCOMPOOP
You have defined a static
method here :
您static
在这里定义了一个方法:
public static long addContact(String name, String email)
Static methods and class variablesare tied to the Class and not to any specific instance of the Class. You cannot use the this
keyword inside it as it refers to the current instance. One of the choice will be to declare the method as instance method removing the static
keyword from the method declaration, if indeed the method logic depends on the state of the current instance.
静态方法和类变量与类相关联,而不与类的任何特定实例相关联。您不能在其中使用this
关键字,因为它指的是当前实例。一种选择是将方法声明为实例方法,static
从方法声明中删除关键字,如果方法逻辑确实取决于当前实例的状态。
I believe the problem in using this
inside a static
method will be that during runtime if your code calls the static method as ClassName.staticMethodName(), the runtime will have no idea how to resolve this
in this context.
我相信在方法this
内部使用的问题static
在于,如果您的代码在运行时将静态方法调用为ClassName.staticMethodName(),则运行时将不知道如何this
在此上下文中解决。
回答by Raghav Sood
this
refers to the current instance of that class.
this
指的是该类的当前实例。
Static methods and objects exist outside of any instance, which is why you are not allowed to use instance specific data, like the current instance, within them
静态方法和对象存在于任何实例之外,这就是为什么您不能在其中使用特定于实例的数据,例如当前实例
回答by Vikalp Jain
You are accessing this in a static function which is not correct
您正在一个不正确的静态函数中访问它
make the function non-static by removing static modifier then it will work fine
通过删除静态修饰符使函数非静态,然后它会正常工作
回答by Suresh Atta
You cannot cannot access fields or methods inside a Static method .
您不能访问静态方法中的字段或方法。
Static methods do not point to any instance of the enclosing class.
So this
keyword this refers to the instance of the class.
所以this
关键字 this 指的是类的实例。
In a static context:
you won't have instance reference to current instance.
So error occurs.
所以出现错误。
回答by Charliemops
You can't use "this" in static context because it implies you have an instance of the object, and statically you can't call to instances.
你不能在静态上下文中使用“this”,因为它意味着你有一个对象的实例,并且静态地你不能调用实例。
Why you need a static class?
为什么需要静态类?
回答by Tala
By looking at this method
通过查看这个方法
// Called when activity is first created
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
I don't think you should be using static class, static field and static method at all.
我认为您根本不应该使用静态类、静态字段和静态方法。
Just create an instance of Activity and work with it. If you need one Activity object through all your program - then use Singleton Pattern. Lazy and Eager instantiation examples are provided.
只需创建一个 Activity 实例并使用它。如果您的所有程序都需要一个 Activity 对象,那么请使用Singleton Pattern。提供了 Lazy 和 Eager 实例化示例。
for example eager initialization will be:
例如,急切初始化将是:
public class DatabaseActivity extends Activity {
private static final DatabaseActivity INSTANCE= new DatabaseActivity();
private DatabaseActivity () {}
public static DatabaseActivity getInstance() {
return INSTANCE;
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); // calls nonstatic method onCreate from Activity class
setContentView(R.layout.activity_main);
}
}
回答by Nomesh Gajare
You have made your class as static.
您已将类设为静态。
Only nested classes can be static. By doing so you can use the nested class without having an instance of the outer class.
只有嵌套类可以是静态的。通过这样做,您可以在没有外部类实例的情况下使用嵌套类。
class OuterClass{
public static class StaticNestedClass{
}
public class InnerClass{
}
public InnerClass getAnInnerClass(){
return new InnerClass();
}
//This method doesn't work
public static InnerClass getAnInnerClassStatically(){
return new InnerClass();
}
}
class OtherClass{
//Use of a static nested class:
private OuterClass.StaticNestedClass staticNestedClass = new OuterClass.StaticNestedClass();
//Doesn't work
private OuterClass.InnerClass innerClass = new OuterClass.InnerClass();
//Use of an inner class:
private OuterClass outerclass= new OuterClass();
private OuterClass.InnerClass innerClass2 = outerclass.getAnInnerClass();
private OuterClass.InnerClass innerClass3 = outerclass.new InnerClass();
}
回答by Birdy
this is a pointer to an object.. in static context you don't have an object.
这是一个指向对象的指针……在静态上下文中,您没有对象。
why is the DatabaseActivy a static class? So make a normal class and create an object of it
为什么 DatabaseActivy 是一个静态类?所以创建一个普通的类并创建它的一个对象