代码之家  ›  专栏  ›  技术社区  ›  isapir

类池。get(className)抛出RuntimeException无法找到类

  •  0
  • isapir  · 技术社区  · 7 年前

    我正在尝试使用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;
            }
        }
    }
    

    但我发现以下错误:

    我试图手动从类路径添加路径,但也没有帮助。即

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

    我错过了什么?谢谢

    1 回复  |  直到 7 年前
        1
  •  1
  •   isapir    7 年前

    问题是类名的分隔符是一个 / 虽然 classPool.get(className) . 定界符,因此修复方法是替换这些字符,即:

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