【问题标题】:How to understand this delegator如何理解这个委托人
【发布时间】:2011-09-14 15:43:32
【问题描述】:

我在看activejdbc的源码,在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(...);
}

我不明白为什么会这样,因为即使没有委托,我们也可以调用这些方法。

【问题讨论】:

    标签: delegates javassist activejdbc


    【解决方案1】:

    可以在此讨论中找到对此的解释:

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

    基本上,主要问题是我们在子类中需要的 Model 类中的方法是静态的。 Java 中的静态类不被继承。这意味着当你这样做时:

    Person.where(...)
    

    您将执行 Model.where() 方法,而不是 Person.where(),因此框架不知道要查询哪个表。 ActiveJDBC 强制模型方法进入子方法,以便在运行时确定要转到哪个表来获取数据。

    【讨论】:

      猜你喜欢
      • 2013-11-26
      • 1970-01-01
      • 2011-01-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多