我必须在运行时动态创建一个类和方法。我为此使用 Javassist:
我要动态创建的方法是:
public Double formula1(FormulaAPI api) {
return api.evaluate(\"L\");
}
如果我使用 将上述整个方法作为方法体传递CtMethod.make(..)
,它可以正常工作。
但我想让它更通用,即我只想return api.evaluate(\"L\");
作为我的方法主体,并想使用 JavaAssist API 方法来设置名称、返回类型等。尝试执行此操作时,我收到错误:
***Exception in thread "main" java.lang.VerifyError:
(class: Formulae, method: formula1 signature: (Lcom/formula/FormulaAPI;)D) Wrong return type in function***
我的问题是:调用时: CtMethod m = new CtMethod(...); 如何将 CtMethod 的返回类型设置为 java.lang.Double 而不是 CtPrimitiveType.doubleType ?
我的整个源代码是:
public class JavaAssistTest {
private static final String className = "Formulae";
private static final String methodName = "formula1";
public static void main(String[] args) throws Exception{
JavaAssistTest jj = new JavaAssistTest();
try {
Class clazz = jj.generateClass(className, methodName);
Object obj = clazz.newInstance();
Method method = clazz.getDeclaredMethod(methodName,FormulaAPI.class);
FormulaAPI api = new FormulaAPI();
method.invoke(obj,api);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (CannotCompileException e) {
e.printStackTrace();
}
}
public Class generateClass(String className, String methodName)
throws CannotCompileException, NotFoundException{
ClassPool pool = ClassPool.getDefault();
CtClass cc = pool.makeClass(className);
ClassLoader classLoader = FormulaAPI.class.getClassLoader();
pool.appendClassPath(new LoaderClassPath(classLoader));
pool.importPackage("com.formula");
String methodBody = "return $1.evaluate(\"L\");";
CtClass apiClass = pool.get("com.formula.FormulaAPI");
CtMethod m = new CtMethod(CtPrimitiveType.doubleType,methodName,new CtClass[]{apiClass},cc);
m.setBody(methodBody);
cc.addMethod(m);
return cc.toClass();
}
}
FormulaAPI 类如下:
public class FormulaAPI {
public Double evaluate(String source){
System.out.println("printing in FormulaAPI ");
return 2.0;
}
}