2016-02-24 26 views
2

對於以下代碼,我收到編譯器錯誤「Getter getLength_inch未關聯到任何字段」。 getLength_inch僅僅是一個實用的方法...Getter未關聯到任何字段

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;} 
} 

似乎RealmObject的任何後代不能執行任何東西比什麼是相關於它的其他領域。這是正確的還是有一些方法來註釋此方法,以便您的處理器忽略它?

感謝

回答

0

似乎RealmObject的任何後代不能執行任何東西比什麼是相關於它的領域

這是正確的事情。 A Realm object只能爲其成員變量擁有getter和setter。

從文檔:

由於代理類是如何覆蓋getter和setter的模型類有一些限制到什麼是允許在一個模型類:

  • 只有私有實例領域。
  • 只有默認的getter和setter方法。
  • 靜態領域,公共和私人。
  • 靜態方法。
  • 實現沒有方法的接口。

這意味着目前不可能擴展除RealmObject之外的其他任何東西,或者覆蓋toString()或equals()等方法。

從Realm 0.87.4開始這是事實。我不知道何時會解除這個限制。

+1

此限制將取消0.88,但在此之前,上述情況屬實。 –

+0

目前,我最終使用_ @ Ignore_註釋添加了屬性_length_inch_。不夠優雅,無緣無故地使用記憶,但那會帶我到0.88結束。謝謝 –

0

由於周圍的工作,以realm.io目前不允許在方法@Ignore,我用內部類,並把額外的功能在它作爲一個「擴展」的限制。這樣,主類保持最小,領域不抱怨,但我有我的額外功能,並保持一些形式的優雅。

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; 
    } 

然後我使用getEx()來訪問「擴展方法」。

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