1 Reply Latest reply on Feb 9, 2011 1:33 PM by cbruguera

    ClassFile write(java.io.DataOutputStream out)  generates empty file!!

    cbruguera

      Hello all, I'm working in a compiler that is generating bytecode, and I wish to only use those javassist classes that work with low-level bytecode (Bytecode, ClassFile, MethodInfo, FieldInfo, etc.). I'm not interested in high level runtime translation of any java code (so I barely need to use CtClass and similar).

       

      The thing is I'm creating a ClassFile object, adding a MethodInfo structure, based on an existent bytecode object (mainCode) which I know is well built. But at the end I'm trying to write the file, and it creates it, but as a 0 byte .class file.

       

      Is there anything that I might be missing?.. Here's my piece of code:

       

       

      ClassFile initClass = getOrCreateClass("InitClass");
      declaring = initClass;
      
      MethodInfo mainMethod = new MethodInfo(initClass.getConstPool(), "main", Descriptor.ofMethod(CtClass.voidType, new CtClass[0]));
      mainMethod.setCodeAttribute(mainCode.toCodeAttribute());
      mainMethod.setAccessFlags(AccessFlag.PUBLIC);
      
      try{
          initClass.addMethod(mainMethod);
      }catch(DuplicateMemberException e){
          Errors.add("Definicion duplicada para \"Accion Principal\"");
      }
      
      writeFile(initClass);
      

       

      The method getOrCreateClass is successfully instantiating a new ClassFile object and returning it.

       

      ...Any ideas?

        • 1. Re: ClassFile write(java.io.DataOutputStream out)  generates empty file!!
          cbruguera

          Oh, I forgot..

           

          writeFile(initClass) will just do this:

           

          public static void writeFile(ClassFile cf){
               try{
                    cf.setVersionToJava5();
                    cf.write(new DataOutputStream(new BufferedOutputStream(new FileOutputStream(cf.getName() + ".class"))));
               }catch(IOException e){
                    Errors.add("Error al escribir el archivo " + name);
               }
          }
          

           

          I really need help