字节码
1 动态生成新的类
- 动态改变类的结构
2 字节码操作库
- BCEL
- ASM
- CGLIB
- Javassist 使用简单
3 简单使用
public class Demo01{
public static void main(String[] args){
ClassPool pool = ClassPook,getDefault();
CtClass cc = pool.makeClass("com.bjsxt.bean.Emp");
CtField f1 = CtField.make("private int empno;", cc);
CtField f2 = CtField.make("private int enameo;", cc);
cc.addField(f1);
cc.addField(f2);
CtConstructor constructor = new Ctconstructor(new CtClass []{});
constructor.setBody("{}");
cc.addConstructor(constructor);
cc.writeFiled("c:/myjava");
}
4 处理类的基本用法
public class Demo02{
public static void main(String[] args){
ClassPool pool = ClassPook,getDefault();
CtClass cc = pool.get("com.bjsxt.bean.Emp");
byte[] bytes = cc.toBytecode();
System.out.printn(cc.getName);
System.out.printn(cc.getSimpleName);
System.out.printn(cc.getSuperClass);
System.out.printn(cc.getInterface);
}
4 处理方法的基本用法
public class Demo03{
public static void main(String[] args){
ClassPool pool = ClassPook,getDefault();
CtClass cc = pool.get("com.bjsxt.bean.Emp");
CtMethod m = CtNewMethod.make()
CtMethod m = newCtMethod(CtClass.intType,"add",new CtClass[] {Ctclass.intType,CtClass.intType},cc);
m.setModifiers(Modifier.PUBLIC;
m.setBody("{return $1 + $2} ");
)
)
}
网友评论