如何在弃用默认构造函数时调用父 class 的构造函数

How to call constructor of parent class when the default constructor is deprecated

我有一个名为 BaseKeyListener 的 class,它扩展了 android.text.method.DigitsKeyListener。我没有在 BaseKeyListener class 中定义构造函数,因此调用了父类的默认构造函数。

从 api 级别 26 开始,DigitsKeyListener 的默认构造函数是 deprecated。为了仍然支持较低的 Android 版本,我必须向 BaseKeyListener 添加一个构造函数,该构造函数有条件地调用父级的构造函数。然而,这会导致另一个错误。

public static abstract class BaseKeyListener extends DigitsKeyListener
{
    public BaseKeyListener()
    {
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
        {
            // api level 26 constructor
            super(null);
        }
        else 
        {
            // api level 1 constructor (deprecated)
            super(); 
        } 
    }
}

我现在遇到的错误:

Call to 'super()' must be first statement in constructor body

我尝试了 shorthand if 语句,但也没有成功。 有 another api 级别 1 构造函数,但不幸的是它也被弃用了。 我该怎么做才能修复这些错误?

我会这样想:

/**
 * only use this if you want to use api level 1
 */
public BaseKeyListener() {
  super(); // implicitly added already
}

/**
 * only use this if you want to use api level 26
 * and add if condition before calling this constructor
 */
public BaseKeyListener(Obect param) {
  super(param);
}

已弃用的构造函数仍然存在于 API 26+ 和 passing in a null locale is the same as calling the default constructor anyway 中。您可以只覆盖默认构造函数,也可以覆盖两者并添加一个静态方法来调用正确的构造函数,具体取决于 Android 它 运行 的版本。

选项 1 - 默认构造函数

public static abstract class BaseKeyListener extends DigitsKeyListener {
  public BaseKeyListener() {
    super(); 
  }
}

选项 2 - 两个私有构造函数

public static abstract class BaseKeyListener extends DigitsKeyListener {
  private BaseKeyListener() {
    super(); 
  }

  private BaseKeyListener(Locale locale) {
    super(locale);
  }

  public static BaseKeyListener newInstance(Locale locale) {
    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
      return new BaseKeyListener(locale);
    } else {
      return new BaseKeyListener();
    }
  }
}