不,您不能通过反射添加方法。在这种情况下,我将使用像Beanshell 2这样的脚本语言。这是一个 DynamicObject 类
public class DynamicObject
{
bsh.Interpreter interpreter = null;
public DynamicObject()
{
interpreter = new bsh.Interpreter();
}
public void addToSource(String... method)
{
try
{
String main = "";
for (int i=0; i<lines.length; i++){
main += lines[i] + "\n";
}
interpreter.eval(main);
}
catch (Exception e)
{
e.printStackTrace();
}
}
public Object invoke(String methodname, Object... args)
{
try
{
return interpreter.getNameSpace().invokeMethod(methodname, args, bsh);
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
public Object invoke(String methodname)
{
return invoke(methodname, (Object[])null);
}
}
现在一个示例动态对象看起来像
DynamicObject testObj = new DynamicObject();
testObj.addToSource(
"public int add ( int a, int b )",
"{",
"return a+b;",
"}"
);
int added = testObj.invoke( "add", 5, 4 ); // is 9