Kotlin 之对 Backing Field 的理解

在对 Kotlin 属性相关内容的学习过程中,遇到了一个新的属性 – Backing Field,对此比较疑惑。在这里按照网上的一种方式暂且把它翻译为 幕后属性 ,本博客为翻阅资料后记录对 幕后属性 的理解。

0x0001 不使用幕后字段的后果

首先需要明确的是 幕后字段 的作用域为 属性默认访问器 或者 在自定义访问器 中通过 field 标识符访问属性,编译器就会为属性自动生成幕后字段。 这就是说其在默认访问器实现了幕后字段,但是当我们在自定义访问器时如果忽略了此操作,那么程序将会报你以崩溃。那么下面我们就看一下这样的情况:

实现了自定义访问器但是未使用幕后字段的 People

1
2
3
4
5
6
7
class People {
var name: String
get() = name
set(value) {
name = value
}
}

在 Main 类中调用 Peoplename 我们看会发生什么:

1
2
3
4
5
6
7
object Main {
val people = People()
@JvmStatic
fun main(arg: Array<String>) {
println(people.name)
}
}

很不幸,如我们所料异常信息如下:

1
2
3
4
5
6
Exception in thread "main" java.lang.StackOverflowError
at People.getName(People.kt:3)
at People.getName(People.kt:3)
at People.getName(People.kt:3)
....
....

报出 java.lang.StackOverflowError 异常并且程序中断。

0x0002 使用幕后字段的原因

那么为什么会出现这样的异常呢?我们来探究以下原因。点击 IDEA 的菜单栏 Tools/Kotlin/Show Kotlin Betycode ,我们可以看到 People 类编译成字节码后的内容,点击 Decompile 按钮进行反编译为 Java 文件,其具体内容如下:

1
2
3
4
5
6
7
8
9
10
11
public final class People {
@NotNull
public final String getName() {
return this.getName();// 此处会递归调用 getName,直到程序抛出堆栈异常
}

public final void setName(@NotNull String value) {
Intrinsics.checkParameterIsNotNull(value, "value");
this.setName(value);// 此处会递归调用 setName,直到程序抛出堆栈异常
}
}

很明显,我们看到当我们在调用 getName()、setName() 时,它的方法体内部又递归调用了其本身,那么程序就会陷入无限的循环中,直到报出 java.lang.StackOverflowError 异常并且程序中断。

所以说,如果使用系统默认的 getter/setter 方法,则不需要显式的声明 Backing Field,但是如果需要自定义 getter/setter 方法,则必须显式的声明 Backing Field

0x0003 在访问器中使用幕后字段

而 幕后字段 的出现就是避免这种情况的发生。使用幕后字段 后的具体代码如下:

1
2
3
4
5
6
7
class People {
var name: String = "Mike"
get() = field
set(value) {
field = value
}
}

此时编译后的文件如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public final class People {
@NotNull
private String name = "Mike";

@NotNull
public final String getName() {
return this.name;
}

public final void setName(@NotNull String value) {
Intrinsics.checkParameterIsNotNull(value, "value");
this.name = value;
}
}

可以看到,在 setName 和 getName 中直接调用了变量 name,没有循环执行 this.getName。
再次运行主程序得到正确的打印日志:Mike

在我们获取变量值 name 的同时对 name 进行处理时,具体代码如下:

1
2
3
4
5
6
7
lass People {
var name: String = "Mike"
get() = field.toUpperCase()
set(value) {
field = value.toString()
}
}

那么相应编译后的代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public final class People {
@NotNull
private String name = "Mike";

@NotNull
public final String getName() {
String var1 = this.name;
if (var1 == null) {
throw new TypeCastException("null cannot be cast to non-null type java.lang.String");
} else {
String var10000 = var1.toUpperCase();
Intrinsics.checkExpressionValueIsNotNull(var10000, "(this as java.lang.String).toUpperCase()");
return var10000;
}
}

public final void setName(@NotNull String value) {
Intrinsics.checkParameterIsNotNull(value, "value");
this.name = value.toString();
}
}

可以看到,在 getName 方法中生成了局部变量 String var1 = this.name;,也避免了递归调用 getName 方法。

0x0004 总结

那么让我们再次来看以下什么是幕后字段,以下是 Suneet Agrawal 的一段描述:

Backing field is an autogenerated field for any property which can only be used inside the accessors(getter or setter) and will be present only if it uses the default implementation of at least one of the accessors, or if a custom accessor references it through the field identifier. This backing field is used to avoid the recursive call of an accessor which ultimately prevents the StackOverflowError.

自己大致翻译如下:

幕后字段自动生成的,它仅仅可以被用在拥有至少一个默认访问器 (getter、setter) 、或者在自定义访问器中通过 field 标识符修饰的属性中。幕后字段可以避免访问器的自递归而导致程序崩溃的 StackOverflowError 异常。

根据幕后属性的使用限制,那么下列情况不会存在幕后属性,因为属性虽然拥有 getter 方法,很明显这是自定义的,不是系统默认的 getter 方法:

1
2
val isEmpty: Boolean
get() = this.size == 0

至此,自己对幕后字段的概念有了初步的认识和理解。


知识链接:
Backing Field in Kotlin
Backing Field in Kotlin — Explained