基础操作
ClassPool classPool = new ClassPool(true);
classPool.appendClassPath(new LoaderClassPath(Thread.currentThread().getContextClassLoader()));
CtClass cc = classPool.makeClass("com.Test1");
//添加字段
CtField name = CtField.make("public String name;",cc);
CtField age = CtField.make("public int age; ",cc);
cc.addField(name);
cc.addField(age);
// 添加无参构造函数
CtConstructor ctConstructor = new CtConstructor(new CtClass[]{}, cc);
ctConstructor.setBody("$0.name = \"池灵\";");
cc.addConstructor(ctConstructor);
// 添加有参构造函数
CtConstructor ctConstructor1 = new CtConstructor(new CtClass[]{classPool.get("java.lang.String"),CtClass.intType}, cc);
ctConstructor1.setBody("{this.name = $1;this.age=$2;}");
cc.addConstructor(ctConstructor1);
//添加方法
CtMethod setName = CtMethod.make("public void setName(String name){this.name = name;}",cc);
CtMethod getName = CtMethod.make("public String getName(){return name;}",cc);
CtMethod setAge = CtMethod.make("public void setAge(int age){this.age= age;}",cc);
CtMethod getAge = CtMethod.make("public int getAge(){return age;}",cc);
cc.addMethod(setName);
cc.addMethod(getName);
cc.addMethod(setAge);
cc.addMethod(getAge);
//修改已有方法体
CtMethod getName1 = cc.getDeclaredMethod("getName");
getName1.insertAfter("System.out.println(\"I'm \" + this.name +String.valueOf(this.age)+ \" years old.\");");
Class<?> aClass = cc.toClass();
Object instance = aClass.newInstance();
Method getName2 = aClass.getDeclaredMethod("getName");
getName2.invoke(instance);
AOP
ClassPool classPool = ClassPool.getDefault();
CtClass ctClass = classPool.get("com.Bar");
//实例化代理工厂
ProxyFactory proxyFactory = new ProxyFactory();
//创建一个类用于继承它
proxyFactory.setSuperclass(ctClass.toClass());
//添加过滤器判断哪些方法需要被代理
proxyFactory.setFilter(new MethodFilter() {
@Override
public boolean isHandled(Method method) {
return true;
}
});
Class<?> aClass = proxyFactory.createClass();
Bar bar = (Bar) aClass.newInstance();
((ProxyObject)bar).setHandler(new MethodHandler() {
@Override
public Object invoke(Object o, Method method, Method method1, Object[] objects) throws Throwable {
System.out.println("1");
//method为被代理的方法,method1为代理方法
Object result = method1.invoke(o, objects);
System.out.println(result);
System.out.println("2");
return result;
}
});
bar.sayHelloBar();