import com.alibaba.dubbo.common.compiler.support.JavassistCompiler;
import javassist.*;
import org.junit.Test;
import java.lang.reflect.InvocationTargetException;
public class JavassistTest {
@Test
public void createClassObj() throws NotFoundException, CannotCompileException,
IllegalAccessException, InstantiationException, NoSuchMethodException,
InvocationTargetException {
ClassPool pool = ClassPool.getDefault();
CtClass ctClass = pool.makeClass("com.enjoy.service.DemoImpl");
CtField nameFild = new CtField(pool.getCtClass("java.lang.String"), "name", ctClass);
nameFild.setModifiers(Modifier.PRIVATE);
ctClass.addField(nameFild);
CtField ageField = new CtField(pool.getCtClass("int"), "age", ctClass);
ageField.setModifiers(Modifier.PRIVATE);
ctClass.addField(ageField);
ctClass.addMethod(CtNewMethod.getter("getName", nameFild));
ctClass.addMethod(CtNewMethod.setter("setName", nameFild));
ctClass.addMethod(CtNewMethod.getter("getAge", ageField));
ctClass.addMethod(CtNewMethod.setter("setAge", ageField));
CtMethod ctMethod = new CtMethod(CtClass.voidType, "sayHello", new CtClass[] {}, ctClass);
ctMethod.setModifiers(Modifier.PUBLIC);
ctMethod.setBody("{\nSystem.out.println(\"hello \" + getName() + \" !\");\n}");
ctClass.addMethod(ctMethod);
Class<?> clazz = ctClass.toClass();
Object obj = clazz.newInstance();
obj.getClass().getMethod("setName", new Class[] {String.class})
.invoke(obj, new Object[] {"peter"});
obj.getClass().getMethod("sayHello", new Class[] {})
.invoke(obj, new Object[] {});
}
@Test
public void createClassByCompile()
throws IllegalAccessException, InstantiationException, NoSuchMethodException,
InvocationTargetException {
JavassistCompiler compiler = new JavassistCompiler();
Class<?> clazz = compiler.compile("public class DemoImpl implements DemoService { public String sayHello(String name) { System.out.println(\"hello \" + name); return \"Hello, \" + name; }}",JavassistTest.class.getClassLoader());
Object obj = clazz.newInstance();
obj.getClass().getMethod("sayHello", new Class[] {String.class}).invoke(obj, new Object[] {"peter"});
}
}