Nie. Nie można dodawać metod za pomocą refleksji. W tym przypadku użyję języka skryptowego, takiego jak Beanshell 2. Oto klasa 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);
}
}
Teraz przykładem dynamiczny obiekt będzie wyglądać
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
http://stackoverflow.com/questions/6680674/can-a-java-class-add-a-method -to-yourself-at-runtime –
Jaki jest * rzeczywisty problem *, który próbujesz rozwiązać. Prawdopodobnie istnieje łatwiejszy sposób na jego wdrożenie. – parsifal
To jest to, czego chcę ..... http: //stackoverflow.com/questions/16482686/adding-getters-setters-to-one-base-class –