2011-09-14 48 views
1

我在讀的來源,發現這些方法在ModelInstrumentation如何理解這個委託人

public void instrument(CtClass modelClass) throws Exception { 
    addDelegates(modelClass); 
    CtMethod m = CtNewMethod.make("public static String getClassName() { return \"" + modelClass.getName() 
      + "\"; }", modelClass); 
    CtMethod getClassNameMethod = modelClass.getDeclaredMethod("getClassName"); 
    modelClass.removeMethod(getClassNameMethod); 
    modelClass.addMethod(m); 
} 

CtClass modelClass = ClassPool.getDefault().get("org.javalite.activejdbc.Model"); 

private void addDelegates(CtClass target) throws NotFoundException, CannotCompileException { 
    CtMethod[] modelMethods = modelClass.getDeclaredMethods(); 
    CtMethod[] targetMethods = target.getDeclaredMethods(); 
    for (CtMethod method : modelMethods) { 

     if (Modifier.PRIVATE == method.getModifiers()) { 
      continue; 
     } 

     CtMethod newMethod = CtNewMethod.delegator(method, target); 

     if (!targetHasMethod(targetMethods, newMethod)) { 
      target.addMethod(newMethod); 
     } else { 
      System.out.println("Detected method: " + newMethod.getName() + ", skipping delegate."); 
     } 
    } 

} 

這個類是用來增強模型類,第一個instrument將首先委託從org.javalite.activejdbc.Model所有非私有方法添加到其子模型類,這意味着它將這種方法添加到子:

public X f(...) { 
    return super.f(...); 
} 

我不明白它爲什麼會這樣做,因爲即使沒有委託,我們也可以調用這些方法。

回答

2

這種解釋可以在這個討論中找到:

https://groups.google.com/forum/#!topic/activejdbc-group/l6KNBi5EPc0

基本上,主要的問題是,在Model類中,我們需要在子類中的方法是靜態的。 Java中的靜態類不會被繼承。這意味着,當你這樣做:

Person.where(...) 

您將執行方法Model.where(),而不是Person.where(),因此,該框架將不知道要查詢的表。 ActiveJDBC將模型方法強制爲子方法,以便在運行時確定要爲數據執行的表。