检测方法时 Javassist 源错误

标签 java reflection instrumentation

我正在尝试在我的一个实体 (com.xxx.entity.Order) 中检测一种方法:

private String getLookupMethodString() {
    return new StringBuilder(
            "public java.lang.String lookupCustomValue(java.lang.String fieldName) throws java.lang.IllegalAccessException, java.lang.reflect.InvocationTargetException, java.beans.IntrospectionException {").append(
            "java.lang.String mappingFieldName =  \"value1\";").append(
            "com.xxx.entity.CustomFieldValue cfv = (com.xxx.entity.CustomFieldValue) new java.beans.PropertyDescriptor(\"customFieldValue\", getClass()).getReadMethod().invoke(this);").append(
            "return (java.lang.String) new java.beans.PropertyDescriptor(mappingFieldName, com.xxx.entity.CustomFieldValue.class).getReadMethod().invoke(cfv);}").toString();
}

public byte[] transform(ClassLoader clazzLoader, String className, Class<?> clazz, ProtectionDomain arg3, byte[] rawBytes) throws IllegalClassFormatException {
    CtClass cl = pool.makeClass(new java.io.ByteArrayInputStream(rawBytes));
    String lookupMethodString = getLookupMethodString();
    CtMethod lookupMethod = CtMethod.make(lookupMethodString, cl); // Error encountered at this line.
    cl.addMethod(lookupMethod);
}

字段 customFieldValue 也在此类中进行了检测,因此我使用反射来获取其值。我执行此操作时遇到的错误是:

[source error] invoke(com.xxx.entity.CustomFieldValue) not found in java.lang.reflect.Method

有人可以帮我解决这个问题吗?

最佳答案

让它工作,问题出在调用方法的调用上。当尝试调用第二个参数为 null 的调用方法时,它起作用了。 (不太确定为什么?)

return (java.lang.String) new java.beans.PropertyDescriptor(mappingFieldName, com.xxx.entity.CustomFieldValue.class).getReadMethod().invoke(cfv, null);}").toString();

关于检测方法时 Javassist 源错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15744161/

相关文章:

java - 使用 Java 代理 (Byte Buddy) 将现有字段从私有(private)转换为公共(public)

java - 如何调试内部错误?

java - Mysql/Glassfish 无效资源 jdbc

java - 当我尝试从 HashSet 中删除不存在的元素时,为什么它没有给出运行时错误?

Java : threads are limited to 25% of the CPU

java - JPA EclipseLink 自定义实体/对象作为 IN 参数

java, 反射, 内部类,

reflection - Kotlin - 获取 KProperty1<T, out R> 的属性类型

通过 JSNI 在 GWT 中实现类似 java.lang.reflect.Proxy 的功能

java - Java EE 容器上的三叶草