我正在尝试修改CtMethod#insertBefore
在超类中声明的方法。但是,使用Javassist似乎是不可能的。
private class AbstractTestDataSource {
public Connection getConnection() throws SQLException {
return connection;
}
}
private class TestDataSource extends AbstractTestDataSource implements DataSource {
public Connection getConnection(String username, String password) throws SQLException {
return connection;
}
// other methods omitted
}
这是我的 ClassFileTransformer
public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined,
ProtectionDomain protectionDomain, byte[] classfileBuffer)
throws Exception {
if (!className.equals("org/example/TestDataSource")) {
return classfileBuffer;
}
final CtClass ctClass = createCtClass(loader, classfileBuffer);
for (CtMethod method : ctClass.getMethods()) {
if (method.getName().equals("getConnection")) {
System.out.print(method.getName());
System.out.println(method.getSignature());
method.insertBefore("System.out.println(\"foo\");");
}
}
return ctClass.toBytecode();
}
当我调用该getConnection(String, String)
方法时,将foo
被打印到控制台,但是如果我调用该getConnection()
方法,则声明的内容AbstractTestDataSource
什么都不会发生。我究竟做错了什么?
编辑
我可以确认已检测到这两种方法,因为这是打印到控制台的内容:
getConnection(Ljava/lang/String;Ljava/lang/String;)Ljava/sql/Connection;
getConnection()Ljava/sql/Connection;
我的解决方案是检查getConnection方法是否在当前类之外的其他类中声明。
if (!ctClass.equals(method.getDeclaringClass())) {
method = overrideMethod(ctClass, method);
}
如果是这样,我创建(并因此重写)getConnection方法并将其委托给超类。
private CtMethod overrideMethod(CtClass ctClass, CtMethod getConnectionMethodOfSuperclass)
throws NotFoundException, CannotCompileException {
final CtMethod m = CtNewMethod.delegator(getConnectionMethodOfSuperclass, ctClass);
ctClass.addMethod(m);
return m;
}
感觉不是理想的解决方案,但效果很好。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句