2011-09-14 62 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将模型方法强制为子方法,以便在运行时确定要为数据执行的表。