利用javassist动态生成类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
package com.deng.javaSsist;

import javassist.CtClass;
import javassist.CtMethod;
import org.junit.Test;
import javassist.ClassPool;

import java.lang.reflect.Method;

public class javassistTest {
@Test
public void testGenerateFirstClass() throws Exception{
//get the class pool
ClassPool pool = ClassPool.getDefault();
//make a class;
CtClass ctClass = pool.makeClass("com.deng.bank.dao.impl.AccountDaoIml");
//make a function
String methodCode = "public void insert(){System.out.println(123);}";
CtMethod method = CtMethod.make(methodCode, ctClass);
ctClass.addMethod(method);
//在内存中生成该类
ctClass.toClass();
//use reflect to instance the object
Class<?> aClass = Class.forName("com.deng.bank.dao.impl.AccountDaoIml");
Object o = aClass.newInstance();
Method insert = aClass.getDeclaredMethod("insert");
//call the function
insert.invoke(o);
}
}

利用javassist动态生成类并实现接口中方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public void testGenerateInterface() throws Exception{
ClassPool pool = ClassPool.getDefault();
CtClass ctClass = pool.makeClass("com.deng.bank.dao.impl.AccountDaoIml");
//generate the interface
CtClass anInterface = pool.makeInterface("com.deng.bank.dao.AccountDao");
//let the class implements the interface
ctClass.addInterface(anInterface);
String methCode = "public void delete(){System.out.println(\"hello world\");}";
CtMethod method = CtMethod.make(methCode, ctClass);
ctClass.addMethod(method);

Class<?> aClass = ctClass.toClass();
AccountDao accountDao = (AccountDao) aClass.newInstance();
accountDao.delete();
}