No. You can't add methods through reflection. In this case, I'll use a scripting language like Beanshell 2. Here's a DynamicObject class
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);
}
}
Now an example dynamic object will look like
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