cohenadair
cohenadair

Reputation: 2072

Android Realm Subclass Instance Methods

I've been reading a lot about Realm and it seems like a very neat tool and I would love to give it a try; however, I've read in a few different places that the Android version doesn't support non-static methods for RealmObject subclasses.

This isn't exactly clear in their documentation. This implies that non-static methods aren't supported, but in their FAQ section, under Why do I need to have getters and setters for all my fields?, they use public, non-static methods.

Also, it makes perfectly clear in this article that:

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.

So I am a little confused. I understand I can't have custom getters/setters; I don't like it, but it's not a deal breaker. But not being able to have any non-static instance methods is another story.

So which is it? Can I or can I not have non-static instance methods in my RealmObject subclasses?

Thanks.

Upvotes: 2

Views: 1254

Answers (2)

EpicPandaForce
EpicPandaForce

Reputation: 81539

Your RealmObject subclasses are supposed to be POJOs that store data.

So they can have private fields, public getters/setters, and static methods/classes/enums/interfaces. That's it.

If you want anything else, you should move it to another class that has a method which takes your realmObject as a parameter.

Upvotes: 0

Hugo Gresse
Hugo Gresse

Reputation: 17879

You are right, you cannot have custom getters and setters.

What is allowed :

  • Only private instance fields.
  • Only default getter and setter methods.
  • Static fields, both public and private.
  • Static methods.
  • Implementing interfaces with no methods.

What is NOT allowed :

  • Custom getters and setters
  • Extends from a non RealmObject
  • Override toString() on equals()
  • Other custom non-static methods

But they are working on it

To be clear, 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.

Source

Upvotes: 4

Related Questions