我正在阅读 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(...);
}
我不明白它为什么这样做,因为即使没有委托,我们也可以调用这些方法。