Re: copy method to different class

James Sasitorn <[email protected]>
Newsgroups gmane.comp.jakarta.bcel.user
Message-ID <[email protected]>
Well I figured it ok. (i have a typo in the code below too).  I manually copied
the MethodGen instead of using copy(). It worked just fine. MethodGen.copy() calls clone(). I never understood what Object.clone() does. So an explicit 
copy worked.

james

On Mon, Jul 19, 2004 at 10:18:46AM -0700, James Sasitorn wrote:
> I am trying to copy methods from one class to another. This is the code I have been woking on. I am getting errors with the resulting constant pool. Is this the correct way to copy a method, or am i misunderstanding the API.
> 
> thanks,
> 
> james
> 
> public static void main(String[] args) {
>    JavaClass j1 = new ClassParser("A.class").parse();
>    JavaClass j2 = new ClassParser("B.class").parse();
>    copyCode(j1,j2);
> }
> 
> public static void copyCode(JavaClass src, JavaClass dest) {
> 
>     ClassGen        cg1 = new ClassGen(dest);
>     ClassGen        cg2 = new ClassGen(dest);
>     ConstantPoolGen cp1 = cg1.getConstantPool();
>     ConstantPoolGen cp2 = cg2.getConstantPool();
> 
>     Method[] methods = src.getMethods();
>     for (int i=0; i< methods.length; i++) {
>         MethodGen m =  new MethodGen(methods[i],
>                                      src.getClassName(),
>                                      cp1);
> 
>         MethodGen m2 = m.copy(cg2.getClassName(), cp2);
> 
>         printCode(new Method[] {m2.getMethod()}, true);
>         cg2.addMethod(m2.getMethod());
>     }
> 
>     JavaClass c3 = cg2.getJavaClass();
>     c3.setConstantPool(cp2.getFinalConstantPool());
> 
>     try {
>         c3.dump("test.class");
>     } catch (IOException e) {
>         System.out.println(e.getStackTrace());
>     }
> }
> 
> ---------------------------------------------------------------------
> To unsubscribe, e-mail: [email protected]
> For additional commands, e-mail: [email protected]
>
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.