tags:

views:

59

answers:

4

I can do this in C++ and Python, but I haven't quite figured it out on java.

My class has a 'MessageReceived' function that my network loop executes when a message comes in. I want the user to be able to write a method in their own class that they want to have run by MessageReceived, but I can't figure out how to pass and execute a method in Java. I can work around it by inheriting the class and overriding MessageReceived, but I'm hoping I can avoid forcing the user to do that.

+1  A: 

The easiest way would be to create an interface that defines the method to be called. That way you can always run the method via Reflection (since you know the method name).

What you are talking about is called "eval" and Java does not have the ability to perform eval like a functional language.

Stupid example using reflection:

      String classname = "MyClass";
  Class klass = Class.forName(classname);
  Class paramTypes[] = {Integer.TYPE, Float.TYPE};
  Method method = klass.getMethod("methodToRun", paramTypes);
  method.invoke(new Integer(1), new Float(1.2f));
amischiefr
Method.invoke requires the instance it is supposed to invoke the method on, not just the parameters.
Yishai
+2  A: 

You'd want the Observer Pattern for allowing other objects to be notified when a message is received.

It's not clear what you're really asking or what problems you have. Is it with design, or is it with actually loading the classes written by the user, or dynamically configuration of the user classes, or something else ?

nos
A: 

Sounds like you're looking for "Closure" functionality, in other words the ability to pass a function as a variable.

http://en.wikipedia.org/wiki/Closure_(computer_science)

Java doesn't currently have this, although there are proposals for adding it to Java 7.

Until then, you could have the user pass in implementation of java.util.Callable, which is basically a wrapper class around one method.

A: 

There are a couple of ways to approach this. The more traditional java way is not to have an arbitrary method that is passed, but rather a defined interface with a method definition. That way your class receives the implementation of the interface, and calls the method on the object.

The other is to pass a Method object together with the instance of the object the method is supposed to be called on. This works fine if you aren't serializing (as Method is not serializable), but won't be anywhere near as elegant as in other languages. You could, of course make your own wrapper class that held the method and the instance, but then you are kind of back to the same interface type solution.

Yishai