Search code examples
javamethodsjava-6

Dynamic Function Creation in Java


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?


Solution

  • In Java, you would normally declare an interface with a method to be called. For example, if your function simply wants to execute some code, you would declare a Runnable and implement its run method.

    public class Foo {
        void bar(Runnable function) {
           for(int i = 0; i < 5; i++) {
               function.run();
           }
        }
    
        static void myFunction() {
             System.out.println("my Function!");
        }
    
        public static void main(String[] ignored) {
             Foo f = new Foo();
             f.bar( new Runnable() { public void run() {
                 myFunction();
             }});
        }
    
    }