【问题标题】:classPool.get(className) throws RuntimeException cannot find classclassPool.get(className) 抛出 RuntimeException 找不到类
【发布时间】:2017-09-04 04:49:21
【问题描述】:

我正在尝试使用 Javassist 编写一个简单的检测代理。

public class Agent implements ClassFileTransformer {

    protected Instrumentation instrumentation;
    protected ClassPool classPool;

    public Agent(Instrumentation instrumentation){

        this.instrumentation = instrumentation;
        this.classPool = ClassPool.getDefault();
        this.instrumentation.addTransformer(this);
    }

    public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {

        try {

            System.out.printf("%s.transform: %s\n", this.getClass().getCanonicalName(), className);

            classPool.insertClassPath(new ByteArrayClassPath(className, classfileBuffer));

            CtClass ctClass = classPool.get(className);  /* <- throws error */
        }
        catch (Exception ex){
            System.out.println(ex);
            return null;
        }
    }
}

但我收到以下错误:

java.lang.RuntimeException: 找不到 java/lang/invoke/MethodHandleImpl: java.lang.invoke.MethodHandleImpl 在 java/lang/invoke/MethodHandleImpl.class 中找到

唯一不抛出此异常的类是我在 IDE (IntelliJ IDEA) 中的项目中的类。

我尝试手动添加类路径中的路径,但这也无济于事。即

String[] cpEntries = System.getProperty("java.class.path").split(File.pathSeparator);
for (String cpEntry : classpathEntries)
    classPool.insertClassPath(cpEntry);

我错过了什么?谢谢!

【问题讨论】:

    标签: bytecode java-bytecode-asm javassist bytecode-manipulation javaagents


    【解决方案1】:

    问题是className的分隔符是/,而classPool.get(className)需要.分隔符,所以解决方法是替换这些字符,即:

    String classNameDotted = className.replace('/', '.');
    CtClass ctClass = classPool.get(classNameDotted);
    

    【讨论】:

      猜你喜欢
      • 2011-03-25
      • 1970-01-01
      • 1970-01-01
      • 2015-01-25
      • 2023-03-24
      • 1970-01-01
      • 2018-03-10
      • 2018-07-10
      • 2011-10-02
      相关资源
      最近更新 更多