Getter is not associated to any field

2020-04-10 01:49发布

问题:

I am getting a compiler error "Getter getLength_inch is not associated to any field" for the following code. getLength_inch is just a utility method...

import io.realm.RealmObject;  
public class Measurement extends RealmObject {
    private float length_mm;

    public void setLength_mm(float c){length_mm = c;}
    public float getLength_mm() { return length_mm;}

    public float getLength_inch() { return length_mm * 0.0394f;}  
}

It seems that any descendant of RealmObject cannot implement anything else than what is pertinent to the its fields. Is this correct or is there some way to annotate this method so that your processor ignores it?

Thanks

回答1:

It seems that any descendant of RealmObject cannot implement anything else than what is pertinent to the its fields

This is correct. A Realm object can only have getters and setters for its member variables.

From the docs:

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().

This is true as of Realm 0.87.4. I do not if/know when this restriction will be lifted.



回答2:

I hope this is not supported. Use a Factory class to achieve this functionality. Write a wrapper class Link

Reference to support issue



回答3:

As a work around to the limitation of realm.io not currently allowing the @Ignore on methods, I used inner classes and put the additional functionality in it as an "extension". This way the main class remain minimal and realm does not complain yet I get to have my additional functionality and keep some form of elegance.

public class Measurement extends RealmObject {
  private float length_mm;
  @Ignore
  private Extension ex;

  public void setLength_mm(float c){length_mm = c;}
  public float getLength_mm() { return length_mm;}

  public class Extension {
     public float getLength_inch() { return length_mm * 0.0394f;}  
  }
  public Extension getEx(){
    if (ex == null) ex = new Extension();
    return ex;
  }

Then I use getEx() to get access to the "extension methods".

float l = myMeasurement.getEx().getLength_inch();


标签: java realm