我正在尝试创建一个动态类及其对象,并尝试使用对象调用类动态方法的方法,但出现以下错误
java.lang.ClassNotFoundException: Eval
这是我的代码,请提出任何更改以使其成功运行
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import javassist.CannotCompileException;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtNewMethod;
public class DyanamicClass {
/**
* @param args
*/
public static void main (String[] args) throws Exception {
createClass();
Object obj=createObject();
Object[] actualParams = new Object[] { new Double(17) };
callMethod("eval", obj,actualParams);
}
public static void createClass()
{
ClassPool pool = ClassPool.getDefault();
CtClass evalClass = pool.makeClass("Eval");
try {
evalClass.addMethod(
CtNewMethod.make("public double eval (double x) { return x ; }", evalClass));
} catch (CannotCompileException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static Object createObject()
{
Object obj=null;
try {
Class clazz = Class.forName("Eval");
obj=clazz.newInstance();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return obj;
}
public static void callMethod(String name,Object obj,Object [] actualParams)
{
Class[] formalParams = new Class[] { double.class };
double result;
try {
Class clazz=Class.forName("Eval");
Method meth = clazz.getDeclaredMethod(name, formalParams);
result = ((Double) meth.invoke(obj, actualParams)).doubleValue();
System.out.println(result);
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}