Skip to content

Instantly share code, notes, and snippets.

@zhanggang807
Created January 19, 2018 08:10
Show Gist options
  • Save zhanggang807/b13dbfbf0fe1370a86793be6c374eab2 to your computer and use it in GitHub Desktop.
Save zhanggang807/b13dbfbf0fe1370a86793be6c374eab2 to your computer and use it in GitHub Desktop.
generator class with javassist lib.
public class MyClassGeneratorByJavassist {
public static void main(String[] args) throws Exception {
ClassPool pool = ClassPool.getDefault();
//创建Programmer类
CtClass cc= pool.makeClass("com.samples.Programmer");
//定义code方法
CtMethod method = CtNewMethod.make("public void code(){}", cc);
//插入方法代码
method.insertBefore("System.out.println(\"I'm a Programmer,Just Coding.....\");");
cc.addMethod(method);
//保存生成的字节码
cc.writeFile(System.getProperty("user.home") + "/Desktop");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment