今天总结了一下.动态执行java代码比较好的有ognl(只能计算表达示),javassist更改class文件方式实现
package com.henglu.test;
import java.security.SecureClassLoader;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtConstructor;
import javassist.CtMethod;
import javassist.NotFoundException;
import ognl.Ognl;
import org.apache.log4j.Logger;
class DirectLoader extends SecureClassLoader {//类加载器,用于加载重复的类
protected DirectLoader() {
super(Test.class.getClassLoader());
}
@SuppressWarnings("rawtypes")
protected Class load(String name, byte[] data) {
return super.defineClass(name, data, 0, data.length);
}
}
class Employee {//实体
private String id;
private int age;
public int getAge() {
return age;
}
public String getId() {
return id;
}
public void setAge(int age) {
this.age = age;
}
public void setId(String id) {
this.id = id;
}
}
/**
* @author zhouxiang
* @version 1.0 2012-10-26 上午9:21:04
*/
public class Test {
private static final Logger LOGGER = Logger.getLogger(Test.class);
/**
* @param args
*/
public static void main(String[] args) {
try {
// OGNL
Employee employee = new Employee();
employee.setId("hl9527");
employee.setAge(26);
LOGGER.info(Ognl.getValue("'id : ' + id + ' , age : '+age*10", employee));
// javassist
testS(" System.out.println(\"" + Test.class.toString() + "...............\");");
testS(" System.out.println(\"" + Test.class.toString() + ".......AAAAAA\");");
} catch (Exception e) {
LOGGER.error("异常", e);
}
}
public static void testS(String str) throws Exception {
String method = "display";
String classPath = "com.henglu.test.Test2";
String className = "TestTest";
ClassPool pool = ClassPool.getDefault();
CtClass ctclass;
CtMethod ctMethod;
try {
ctclass = pool.get(className);
ctclass.defrost();// 解冻,(类加载器加载后就会冻结)
ctMethod = ctclass.getDeclaredMethod(method);
ctMethod.setBody(str);
} catch (NotFoundException e) {
ctclass = pool.makeClass(className);// 创建类
ctclass.addInterface(pool.get(classPath));// 实现接口
CtConstructor cons = new CtConstructor(null, ctclass);// 实现构造方法
cons.setBody(";");
ctclass.addConstructor(cons);
ctMethod = new CtMethod(CtClass.voidType, method, null, ctclass);// 新建方法
ctMethod.setBody(str);
ctclass.addMethod(ctMethod);
}
DirectLoader directLoader = new DirectLoader();// 类加载器,用于重复加载名称相同的类
Test2 test2 = (Test2) directLoader.load(className, ctclass.toBytecode()).newInstance();
test2.display();
}
}
Test2接口
package com.henglu.test;
/**
* @author zhouxiang
* @version 1.0 2012-10-26 上午10:24:37
*/
public interface Test2 {
public void display();
}
输出结果
2012-10-26 15:43:54,369 [com.henglu.test.Test]-[INFO] id : hl9527 , age : 260 class com.henglu.test.Test............... class com.henglu.test.Test.......AAAAAA