處理類的基本用法
測試產生新的方法
//通過反射呼叫新生成的方法
修改已有的方法資訊,修改方法體的內容
//通過反射呼叫新生成的方法
屬性的操作
構造方法的操作
獲得註解的操作
package com.lzy.assist;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import javassist.CannotCompileException;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtConstructor;
import javassist.CtField;
import javassist.CtMethod;
import javassist.CtNewMethod;
import javassist.Modifier;
import javassist.NotFoundException;
public class Demo02 {
public static void test01() throws Exception {
ClassPool pool=ClassPool.getDefault();
CtClass cc=pool.get("com.lzy.assist.Emp");
byte[] bytes=cc.toBytecode();
System.out.println(Arrays.toString(bytes));
System.out.println(cc.getName());
System.out.println(cc.getSimpleName());
System.out.println(cc.getSuperclass());
System.out.println(cc.getInterfaces());
}
public static void test02() throws Exception {
ClassPool pool=ClassPool.getDefault();
CtClass cc=pool.get("com.lzy.assist.Emp");
CtMethod m=new CtMethod(CtClass.intType,"add",
new CtClass[] {CtClass.intType,CtClass.intType},cc);
m.setModifiers(Modifier.PUBLIC);
m.setBody("{System.out.println(\"www.baidu.com\");return $1+$2;}");
cc.addMethod(m);
Class clazz=cc.toClass();
Object obj = clazz.getDeclaredConstructor().newInstance();
Method method = clazz.getDeclaredMethod("add", int.class,int.class);
Object result = method.invoke(obj, 200,300);
System.out.println(result);
}
public static void test03() throws Exception {
ClassPool pool=ClassPool.getDefault();
CtClass cc=pool.get("com.lzy.assist.Emp");
CtMethod cm=cc.getDeclaredMethod("sayHello",new CtClass[] {CtClass.intType});
cm.insertBefore("System.out.println($1);System.out.println(\"start!!!\");");
cm.insertAt(9, "int b=3;System.out.println(\"b=\"+b);");
cm.insertAfter("System.out.println(\"end!!!\");");
Class clazz=cc.toClass();
Object obj=clazz.getDeclaredConstructor().newInstance();
Method method = clazz.getDeclaredMethod("sayHello", int.class);
method.invoke(obj, 300);
}
public static void test04() throws Exception {
ClassPool pool=ClassPool.getDefault();
CtClass cc=pool.get("com.lzy.assist.Emp");
CtField f1 = new CtField(CtClass.intType,"salary",cc);
f1.setModifiers(Modifier.PRIVATE);
cc.addField(f1);
cc.addMethod(CtNewMethod.getter("getSalary", f1));;
cc.addMethod(CtNewMethod.getter("setSalary", f1));;
}
public static void test05() throws Exception {
ClassPool pool = ClassPool.getDefault();
CtClass cc = pool.get("com.lzy.assist.Emp");
CtConstructor[] cs = cc.getConstructors();
for (CtConstructor c : cs) {
System.out.println(c.getLongName());
}
}
public static void test06() throws Exception{
CtClass cc = ClassPool.getDefault().get("com.lzy.assist.Emp");
Object[] all = cc.getAnnotations();
Author a = (Author)all[0];
String name = a.name();
int year = a.year();
System.out.println("name: " + name + ", year: " + year);
}
public static void main(String[] args) throws Exception {
test06();
}
}