2015-09-18 39 views
0

我使用Scala作爲我的語言。我使用Google Objectify作爲持久性API來將對象存儲到Google App Engine的數據存儲中。任何要通過Objectify存儲在Google App Engine數據存儲中的類都必須在該類的前面添加一個@Entity註釋。您通常將此註釋應用於您自己的類,以便在您自己的應用程序或域中使用。在我的一個類中,我希望能夠定義一個類型爲Option [String]的類屬性。爲了做到這一點,我需要能夠將@Entity或@Subclass註解(Objectify註釋)應用於Option類。但是這是一種內置的Scala語言類型。有沒有辦法使用隱式類或類型或Scala宏來對語言進行「猴子修補」,以允許我在事後將該註釋添加到內置的Scala語言類型中?是否有可能使用註釋來修補scala final class?

回答

0

最簡單的解決方案是定義您自己的類,相當於Option和隱式轉換從/到Option。否則,在Scala本身中沒有辦法這樣做,但是您可以使用字節碼操作庫之一,如ASM或Javassist。有一個爲ASM here(但似乎不完整)動態添加註釋的示例,另一個用於Javassist here。 Javassist似乎更容易使用(不翻譯爲斯卡拉,但它是微不足道的):

import java.lang.reflect.Field; 

import javassist.ClassPool; 
import javassist.CtClass; 
import javassist.CtField; 
import javassist.bytecode.AnnotationsAttribute; 
import javassist.bytecode.ClassFile; 
import javassist.bytecode.ConstPool; 
import javassist.bytecode.annotation.Annotation; 

public class AddingAnnotationDynamically { 
    public static void main(String[] args) throws Exception { 
     ClassPool cp = ClassPool.getDefault(); 
     CtClass cc = cp.get("scala.Option"); 
     // Without the call to "makePackage()", package information is lost 
     cp.makePackage(cp.getClassLoader(), pkgName); 
     ClassFile cfile = cc.getClassFile(); 
     ConstPool cpool = cfile.getConstPool(); 

     AnnotationsAttribute attr = 
       new AnnotationsAttribute(cpool, AnnotationsAttribute.visibleTag); 
     Annotation annot = new Annotation(annotationName, cpool); 
     attr.addAnnotation(annot); 
     cfile.addAttribute(attr); 
     // Changes are not persisted without a call to "toClass()" 
     Class<?> c = cc.toClass(); 
    } 
} 
+0

謝謝。我會嘗試你的第一個建議。 – bjenkins001

相關問題