So I'm trying to figure out if there is some method to dynamically create/assign a method to a class in Java. If it were C, I would just do it as follows using pointers:
public class Foo {
void bar(void *ptr) {....}
};
int main() {
Foo f = new Foo();
f.bar({"my function" ...})
}
However, Java of course has no pointers, so is there any way to get a similar functionality out of a Java application?
In java it is achieved by something called anonymous classes, here is an example -
If you really want to change classes at runtime, the only way is to actually modify the bytecode, assuming your set-up allows it (Java security would normally kick in). That said, there's an
java.lang.instrument
package in Java 6 which may help:http://download.oracle.com/javase/6/docs/api/java/lang/instrument/package-summary.html
You might find the cglib project of use also:
http://sourceforge.net/projects/cglib/
To generate truly dynamic methods you need a bytecode-manipulation library, such as Javassist or cglib.
You can use the Java Scripting API, create the function as a Script and call it. But only do this if your functions are really completely defineable at runtime, because interpreting scripts is always slower than implementing it in native Java.
Here's a link to how you can use the built in runtime version of javac to compile classes you define on the fly.
See http://functionaljava.org/ for a whole functional library for Java.