public class Dema {
//获取原方法信息
public static void test01() throws Exception
{
ClassPool pool=ClassPool.getDefault();
CtClass cc=pool.get("cn.sxt.in.Emp"); //获得已有的类
byte[] bytes=cc.toBytecode(); //转换成字节码
System.out.println(cc.getName()); //获取类名
System.out.println(cc.getSimpleName()); //获取简要类名
System.out.println(cc.getSuperclass()); //获取父类
System.out.println(Arrays.toString(bytes));
System.out.println(cc.getInterfaces()); //获取接口,返回的是数组
}
//添加方法
public static void test02() throws Exception
{
ClassPool pool =ClassPool.getDefault();
CtClass cc=pool.get("cn.sxt.in.Emp");
//创建新方法
CtMethod m=CtNewMethod.make("public int add(int a,int b){return a+b;}", cc);
//创建新方法
CtMethod m2=new CtMethod(CtClass.intType,"add2",new CtClass[] {CtClass.intType,CtClass.intType},cc);
m2.setModifiers(Modifier.PUBLIC); //设置权限
m2.setBody("{System.out.println(\"yes\");return $1+$2;}"); //占位符代替形参名
cc.addMethod(m2);
cc.addMethod(m);
//通过反射调用新生成的方法
Class clazz=cc.toClass();
Object obj=clazz.newInstance(); //通过调用Emp的无参构造器,创建新的Emp对象
Method method=clazz.getDeclaredMethod("add2",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("cn.sxt.in.Emp");
CtMethod cm=cc.getDeclaredMethod("sayHello",new CtClass[] {CtClass.intType});
//在方法开头添加内容
cm.insertBefore("System.out.println($1);System.out.println(\"start\");");
//在某一行前面加代码
cm.insertAt(8, "System.out.println(\"ugly\");");
//在方法后面加内容
cm.insertAfter("System.out.println(\"end\");");
Class clazz=cc.toClass();
Object obj=clazz.newInstance(); //通过调用Emp的无参构造器,创建新的Emp对象
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("cn.sxt.in.Emp");
CtField f1=CtField.make("private int emm;", cc);
CtField f2=new CtField(CtClass.intType,"emm2",cc);
f2.setModifiers(Modifier.PRIVATE);
cc.addField(f1,"100"); //传默认值
cc.addField(f2);
//cc.getDeclaredField("ename"); 获取指定属性
//增加相应的set和get方法
cc.addMethod(CtNewMethod.getter("getEmm2", f2));
cc.addMethod(CtNewMethod.getter("setEmm2", f2));
}
//构造器
public static void test05() throws Exception
{
ClassPool pool=ClassPool.getDefault();
CtClass cc=pool.get("cn.sxt.in.Emp");
CtConstructor[] cs= cc.getConstructors();
for(CtConstructor c:cs)
{
System.out.println(c.getLongName());
}
}
//调用注解
public static void test06() throws Exception
{
ClassPool pool=ClassPool.getDefault();
CtClass cc=pool.get("cn.sxt.in.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();
}
}
网页题目:javajavassist库处理类的基本用法
转载来源:
http://kswsj.cn/article/gegije.html