/**
* 产生新的方法
* @throws Exception
*/
public static void test01() throws Exception {
ClassPool pool = ClassPool.getDefault();
CtClass cc = pool.get("包名 . 类名");
//两种方式产生新的方法
// CtMethod m1 = CtMethod.make("public int getEmpNo(){return empNo;}", cc);
CtMethod m2 = new CtMethod(CtClass.intType, "add",
new CtClass[] {CtClass.intType,CtClass.intType} , cc);
m2. setModifiers(Modifier.PUBLIC);
m2. setBody("return $1 + $2;");
// cc.addMethod(m1);
cc. addMethod(m2);
//通过反射调用新生成的方法
Class c = cc.toClass();
Object obj = c.newInstance(); //调用无参构造来创建对象
Method method = c.getDeclaredMethod("add", int.class,int.class);
Object result = method.invoke(obj, 100,300);
System.out.println(result);
}
* 产生新的方法
* @throws Exception
*/
public static void test01() throws Exception {
ClassPool pool = ClassPool.getDefault();
CtClass cc = pool.get("包名 . 类名");
//两种方式产生新的方法
// CtMethod m1 = CtMethod.make("public int getEmpNo(){return empNo;}", cc);
CtMethod m2 = new CtMethod(CtClass.intType, "add",
new CtClass[] {CtClass.intType,CtClass.intType} , cc);
m2. setModifiers(Modifier.PUBLIC);
m2. setBody("return $1 + $2;");
// cc.addMethod(m1);
cc. addMethod(m2);
//通过反射调用新生成的方法
Class c = cc.toClass();
Object obj = c.newInstance(); //调用无参构造来创建对象
Method method = c.getDeclaredMethod("add", int.class,int.class);
Object result = method.invoke(obj, 100,300);
System.out.println(result);
}
/**
* 新的属性并生成get 和 set
* @throws Exception
*/
* 新的属性并生成get 和 set
* @throws Exception
*/
public static void test04() throws Exception {
ClassPool pool = ClassPool.getDefault();
CtClass cc = pool.get("JavassistTest.TestClass_Emp");
ClassPool pool = ClassPool.getDefault();
CtClass cc = pool.get("JavassistTest.TestClass_Emp");
//两种方式产生新的属性
// CtField f1 = CtField. make("private int age", cc);
CtField f2 = new CtField(CtClass.intType,"age",cc);
f2. setModifiers(Modifier.PRIVATE);
cc. addField(f2);
cc.getDeclaredField("age");//获得这个属性
// CtField f1 = CtField. make("private int age", cc);
CtField f2 = new CtField(CtClass.intType,"age",cc);
f2. setModifiers(Modifier.PRIVATE);
cc. addField(f2);
cc.getDeclaredField("age");//获得这个属性
//增加相应的get set方法
cc.addMethod(CtNewMethod.getter("getAge", f2));
cc.addMethod(CtNewMethod.getter("setAge", f2));
cc.addMethod(CtNewMethod.getter("getAge", f2));
cc.addMethod(CtNewMethod.getter("setAge", f2));
}
* 修改已有的方法
* @throws Exception
*/
public static void test03() throws Exception{
ClassPool pool = ClassPool.getDefault();
CtClass cc = pool.get("JavassistTest.TestClass_Emp");
CtMethod m1 = cc.getDeclaredMethod("sayHello",new CtClass [] {CtClass.intType});
m1. insertBefore("System.out.println($1);System.out.println(\"start!!!\");");
Class c = cc.toClass();
Object obj = c.newInstance(); //调用无参构造来创建对象
Method method = c.getDeclaredMethod("sayHello", int.class);
Object result = method.invoke(obj,300);
System.out.println(result);
}