码迷,mamicode.com
首页 > 编程语言 > 详细

javassist动态修改class

时间:2014-08-01 13:29:51      阅读:286      评论:0      收藏:0      [点我收藏+]

标签:java   os   io   for   ar   new   ef   c   

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!");
    }
}

javassist动态修改class,布布扣,bubuko.com

javassist动态修改class

标签:java   os   io   for   ar   new   ef   c   

原文地址:http://www.cnblogs.com/zhangrumingbj/p/3884717.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!