javassist动态修改class

时间:2022-09-20 06:12:18

import java.io.IOException;
import java.io.PrintWriter;

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

/**
 * @author zhangruming
 *
 */
public class calss2 {

/**
     * @param args
     * @throws NotFoundException
     * @throws CannotCompileException
     * @throws IllegalAccessException
     * @throws InstantiationException
     * @throws IOException
     * @throws ClassNotFoundException
     */
    public static void main(String[] args) throws NotFoundException, CannotCompileException, InstantiationException, IllegalAccessException, IOException, ClassNotFoundException {

ClassPool cp = ClassPool.getDefault();
        CtClass cc = cp.get("calss1");
        CtMethod cm = cc.getDeclaredMethod("sayhi");
        cm.setBody("System.out.println(\"hi class1\");");
        calss1 calss1 = (calss1) cc.toClass().newInstance();
        
        calss1.kk();
        
        String javaStr = "class calss3{public void sayhi(){System.out.println(\"hi!\");}}";
        String className = "calss3";
        PrintWriter   writer   =   new   PrintWriter(className + ".java");
        
        writer.close();
        Runtime.getRuntime().exec( "javac   -d   " + className    +   ".java ");
        Class   c   =   Class.forName(className);
          calss3  o   =   (calss3) c.newInstance();
          o.kk();
    }

}

class calss1{
    public void sayhi()
    {
        System.out.println("hi!");
    }
}