简体   繁体   English

检查是否已初始化最终实例变量

[英]Checking if a final instance variable has been initialized

I am still learning Java but I am not sure why this is causing compile time error: 我还在学习Java,但我不确定为什么会导致编译时错误:

public class AnswerRepository implements IAnswerRepository
{
    private final static SQLiteDatabase database;

    public AnswerRepository(Activity activity)
    {
        if(database != null)
        {
            database = DbOpenHelper.getInstance(activity);
        }
    }
}

I am just trying to check if a final variable has been assigned first before assigning a value to it. 我只是想在为其分配值之前检查是否先分配了最终变量。 But it seems compile time checking doesn't like it. 但似乎编译时检查不喜欢它。 Why is that? 这是为什么?

在此输入图像描述

final variables can only be initialized once. final变量只能初始化一次。 Normally, they must be initialized in the constructor, but if they are static , then they need to be initialized when they are defined, like this: 通常,它们必须在构造函数中初始化,但如果它们是static ,那么在定义它们时需要对它们进行初始化,如下所示:

private final static SQLiteDatabase database = new SQLiteDatabase(...);

or, you can initialize it later: 或者,您可以稍后将其初始化:

private static SQLiteDatabase database;

static variables will be initialized before object constructors are called. static变量将在调用对象构造函数之前初始化。 So in this case, database will always be null and since it is null , re-initializing it in the object constructor will cause a compile time error. 因此,在这种情况下, database将始终为null ,因为它为null ,所以在对象构造函数中重新初始化它将导致编译时错误。

You can't initialize final static variable on constructor. 您无法在构造函数上初始化final static变量。 To initialize use inline statement, 要初始化使用内联语句,

private final static SQLiteDatabase database= DbOpenHelper.getInstance(activity);

or, use static block. 或者,使用静态块。

 private final static SQLiteDatabase database;

 static{
       database = DbOpenHelper.getInstance(activity);
 }

Initalize database variable. 初始化数据库变量。

private final static SQLiteDatabase database = null;

FYI : You should initialize a static final variable either in a static initializer, or directly. 仅供参考:您应该在静态初始化程序中或直接初始化静态最终变量。 So either 所以要么

static final SQLiteDatabase database = null;

Or 要么

static final JButton button;

static {
  button = new JButton();
}

Read this doc for more info. 阅读此文档了解更多信息。

At this point: 这一点:

if (database != null)

It's impossible that database has a non-null value: you didn't initialize it at the declaration, nor at any static initialization block. database 不可能具有非空值:您没有在声明处初始化它,也没有在任何静态初始化块初始化它。 So the compiler is correctly complaining that the variable is null at this point. 所以编译器正确地抱怨此变量为null

Either initialize it at the declaration: 在声明中初始化它:

private final static SQLiteDatabase database = ...;

Or use a static initialization block: 或者使用静态初始化块:

static {
    database = ...;
}

Final static member must be initialized in static way. 最终的静态成员必须以静态方式初始化。 In your case. 在你的情况下。 You need remove final keyword. 您需要删除final关键字。

Static variables are belong to Class not to any instances of that class. 静态变量属于Class而不属于该类的任何实例。 And they will be initialized in class loading time. 它们将在课程加载时间初始化。 So, initializing it in the constructor doesn't make any sense. 因此,在构造函数中初始化它没有任何意义。 Since for every instance creation, that will be reinitialized. 因为每次创建实例,都会重新初始化。 This may cause problems to you. 这可能会给您带来麻烦。 Use static initialization block to initialize them. 使用静态初始化块初始化它们。

Final variable either be null initially & then when it has reference then it wont change. 最终变量最初为空,然后当它有参考时,它就不会改变。 so you have to put 所以你必须把

database = null;

or else you have to assign some value out side of if condition. 否则你必须在if条件下指定一些值。

so if if does not execute then also it have to assign value. 所以如果if没有执行那么它也必须赋值。

static members must be intialized in a 静态成员必须初始化为

static { } 静态的 { }

block

  • also you are using an IDE most IDE's have strict code error setting that are different than compilers so you might need to check that as well if above doesn't resolve it * 你也在使用IDE,大多数IDE都有严格的代码错误设置,这些设置与编译器不同,所以你可能需要检查一下,如果上面没有解决它*

Since you are trying to create instance of database variable in AnswerRepository constructor, I don't see any necessity why there is a null check in the constructor. 由于您尝试在AnswerRepository构造函数中创建数据库变量的实例,因此我没有看到为什么在构造函数中存在空检查的必要性。

This should have been handled in DbOpenHelper.getInstance(activity) not here. 这应该在DbOpenHelper.getInstance(activity)中处理,而不是在这里。

Your code can be like the below one and will serve your purpose. 您的代码可以如下所示,并将满足您的目的。

public class DbOpenHelper
{
   private static SQLiteDatabase database;

  public static SQLiteDatabase getInstance(Activity activity)
  {
      if( null == database )
      {
          database = new SQLiteDatabase(...);
      }
      return database;
  }
}

There are many good ways of creating singleton. 创建单身人士有很多好方法。 Choose a good one. 选择一个好的。 The one that is posted above is just for an example. 上面发布的那个只是一个例子。

As mentioned by others, but the below code in static block 正如其他人所提到的,但下面的代码在静态块中

database = DbOpenHelper.getInstance(activity);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM