mardi 20 décembre 2016

Java - How to link a class created by Javassist with JVM

This is the first time I ever use Javassist, I created a class using javassist and I added some methods to it, and now I want to know how to link it with the JVM. Here is the code I wrote:

package up.coo.tp10;

import java.io.DataOutputStream;
import java.io.FileOutputStream;

import javassist.CannotCompileException;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;
import javassist.CtNewMethod;

public class Main {

/**
 * @param args
 */
public static void main(String[] args) {
    // TODO Auto-generated method stub

    ClassPool pool = ClassPool.getDefault();
    CtClass cc = pool.makeClass("COOUnitGenerator");
    try {
        CtMethod cm4 = CtNewMethod.make("public void test4(){System.out.println(\" === Method 4 === \");}", cc);
        CtMethod cm1 = CtNewMethod.make("public void test1(){System.out.println(\" === Method 1 === \");}", cc);
        CtMethod cm3 = CtNewMethod.make("public void test3(){System.out.println(\" === Method 3 === \");}", cc);
        CtMethod cm2 = CtNewMethod.make("public void test2(){System.out.println(\" === Method 2 === \");}", cc);
        CtMethod cmSetUp = CtNewMethod.make("public void setUp(){System.out.println(\" === Set Up === \");}", cc);

        cc.addMethod(cm4);
        cc.addMethod(cm1);
        cc.addMethod(cm3);
        cc.addMethod(cm2);
        cc.addMethod(cmSetUp);

    } catch (CannotCompileException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}





Aucun commentaire:

Enregistrer un commentaire