接口:
package javassist;
public interface IHello {
public void sayHello(String name);
}
实现:
package javassist;
/**
*ClassPool.get(String className):返回类名对应编译时的类
* Class.class.getName():获取Class类的全类名
*/
public class MakeClassTestInterface {
/*对接口--IHello进行增强,添加方法体*/
public static void main(String[] args) throws NotFoundException, CannotCompileException, IllegalAccessException,
InstantiationException {
/**
* 设置classpath路径:默认类加载器加载路径
*/
ClassPool classPool = new ClassPool(true);
//ClassPool classPool = new ClassPool();
//classPool.insertClassPath(new LoaderClassPath(MakeClassTestInterface.class.getClassLoader()));
/**
* 创建新类--实现接口
*/
CtClass ctClass = classPool.makeClass("javassist.Hello");
ctClass.addInterface(classPool.get(IHello.class.getName()));
/**
* 添加方法
* CtMethod(CtClass returnType, String mname, CtClass[] parameters, CtClass declaring)
*/
CtClass returnType=classPool.get(void.class.getName());
String mname="sayHello";
CtClass parameter=classPool.get(String.class.getName());
CtClass[] parameters=new CtClass[]{parameter};
CtMethod ctMethod = new CtMethod(returnType,mname,parameters,ctClass);
/*设置方法体*/
String body="{"+"System.out.println(\"Hello\"+\"--\"+$1);"+"}";
ctMethod.setBody(body);
ctClass.addMethod(ctMethod);
Class<?> clz = ctClass.toClass();
IHello o = (IHello) clz.newInstance();
o.sayHello("lan");
}
}