kotlin之object关键字的应用场景
对象声明(object declaration 单例模式)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| object UserManager { fun saveUser() }
public final class UserManager { public static final UserManager INSTANCE;
public final void saveUser() { }
private UserManager() { }
static { UserManager var0 = new UserManager(); INSTANCE = var0; } }
|
在kotlin和java代码中,它们的调用方式有点差别:
- kotlin代码调用:UserManager.saveUser()
- java代码调用:UserManager.INSTANCE.saveUser();
伴生对象(companion object 静态成员)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| class App { companion object { fun getAppContext() {} } }
public final class App { public static final App.Companion Companion = new App.Companion((DefaultConstructorMarker)null);
public static final class Companion { public final void getAppContext() { }
private Companion() { }
public Companion(DefaultConstructorMarker $constructor_marker) { this(); } } }
|
与对象声明类似,它们在kotlin和java代码中的调用方式也有点差别:
- kotlin代码调用:App.getAppContext()
- java代码调用:App.Companion.getAppContext();
对象表达式(object expression 匿名内部类)
对象表达式常用来作为匿名内部类的实现
1 2 3 4 5 6 7 8 9 10 11
| private val callBack = object : CallBack { override fun onSuccess() {} override fun onFailure() {} }
btn.setOnClickListener(object : View.OnClickListener { override fun onClick(v: View) { TODO("Not yet implemented") } })
|
扩展
使用kotlin自带的注解:@JvmStatic或者@JvmField,这样就可以和kotlin调用保持一致。
@JvmStatic既可以修饰属性,也可以修饰方法;而@JvmField只能修饰属性
对于对象声明:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| object UserManager { @JvmStatic fun saveUser() }
public final class UserManager { public static final UserManager INSTANCE;
@JvmStatic public static final void saveUser() { }
private UserManager() { }
static { UserManager var0 = new UserManager(); INSTANCE = var0; } }
|
// java调用
UserManager.saveUser();
对于伴生对象:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| class App { companion object{ @JvmStatic fun getAppContext() {} } }
public final class App { public static final App.Companion Companion = new App.Companion((DefaultConstructorMarker)null);
@JvmStatic public static final void getAppContext() { Companion.getAppContext(); }
public static final class Companion { @JvmStatic public final void getAppContext() { }
private Companion() { }
public Companion(DefaultConstructorMarker $constructor_marker) { this(); } } }
|
// java调用
App.getAppContext();
参考文章:
https://www.jianshu.com/p/1a0cf2ca87cc