[英]How to call constructor of parent class when the default constructor is deprecated
I have a class called BaseKeyListener that extends android.text.method.DigitsKeyListener. 我有一个名为BaseKeyListener的类,该类扩展了android.text.method.DigitsKeyListener。 I didn't define a constructor in the BaseKeyListener class so the parents default constructor was called.
我没有在BaseKeyListener类中定义构造函数,因此调用了父级默认构造函数。
As of api level 26 the default constructor of DigitsKeyListener is deprecated . 从API级别26开始, 不建议使用 DigitsKeyListener的默认构造函数。 In order to still support lower Android versions I would have to add a constructor to BaseKeyListener that conditionally calls the constructor of the parent.
为了仍然支持较低的Android版本,我必须向BaseKeyListener添加一个构造函数,该构造函数有条件地调用父级的构造函数。 However this results in another error.
但是,这将导致另一个错误。
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();
}
}
}
The error I'm getting now: 我现在得到的错误:
Call to 'super()' must be first statement in constructor body
调用“ super()”必须是构造函数主体中的第一条语句
I tried a shorthand if statement but that also didn't do the trick. 我尝试了一个简写的if语句,但这也没有解决问题。 There was another api level 1 constructor but unfortunately it's also deprecated.
还有另一个 api 1级构造函数,但不幸的是它也已弃用。 What can I do to fix these errors?
我该如何解决这些错误?
I would think something like this: 我会这样想:
/**
* 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);
}
The deprecated constructor still exists in API 26+ and passing in a null locale is the same as calling the default constructor anyway . 不推荐使用的构造函数仍存在于API 26+中,并且传递空语言环境与无论如何都调用默认构造函数相同 。 You can either just override the default constructor or override both and add a static method to call the right constructor depending on which version of Android it's running on.
您可以覆盖默认的构造函数,也可以覆盖两者,然后添加静态方法来调用正确的构造函数,具体取决于运行的Android版本。
public static abstract class BaseKeyListener extends DigitsKeyListener {
public BaseKeyListener() {
super();
}
}
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();
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.