我读了很多关于 Realm 的文章,它看起来是一个非常简洁的工具,我很想尝试一下;但是,我在几个不同的地方读到 Android 版本不支持 RealmObject 子类的非静态方法。
这在 their documentation 中并不完全清楚。这意味着不支持非静态方法,但在 FAQ 部分的“为什么我的所有字段都需要 getter 和 setter?”下,它们使用公共(public)的非静态方法。
此外,this 文章中非常清楚地表明:
You will get compilation errors for using ANY other methods in the model class. Think about this for a moment ...
Yeah.. you can not have toString(), Static methods, not even other behavior methods in your model classes.
所以我有点困惑。我知道我不能有自定义的 getter/setter;我不喜欢它,但这并不影响交易。但无法拥有任何非静态实例方法则是另一回事了。
那么它是哪一个呢?我的 RealmObject 子类中是否可以有非静态实例方法?
谢谢。
最佳答案
你是对的,你不能有自定义的 getter 和 setter。
允许的内容:
- 仅限私有(private)实例字段。
- 只有默认的 getter 和 setter 方法。
- 静态字段,包括公共(public)字段和私有(private)字段。
- 静态方法。
- 实现不带方法的接口(interface)。
不允许做什么:
- 自定义 getter 和 setter
- 从非 RealmObject 扩展
- 重写
equals()
上的toString()
- 其他自定义非静态方法
需要明确的是,RTFM:
Be aware that the getters and setters will be overridden by the generated proxy class used in the back by RealmObjects, so any custom logic you add to the getters & setters will not actually be executed.
Limitations
Due to how the proxy classes override getters and setters in the model classes there are some restrictions to what is allowed in a model class.Due to how the proxy classes override getters and setters in the model classes there are some restrictions to what is allowed in a model class:
Only private instance fields. Only default getter and setter methods. Static fields, both public and private. Static methods. Implementing interfaces with no methods.
This means that it is currently not possible to extend anything else than RealmObject or to override methods like toString() or equals(). Also it is only possible to implement interfaces.
关于java - Android Realm 子类实例方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31991104/