The moose likes Java in General and the fly likes Function Pointer Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Function Pointer" Watch "Function Pointer" New topic

Function Pointer

Amit Lonkar

Joined: Dec 12, 2001
Posts: 25
Hi All!!!
In "C" programming, we can have a pointer to a function. Can we have a reference to a function stored in an Object in Java.
David O'Meara

Joined: Mar 06, 2001
Posts: 13459

Have you looked into reflection?
If you look at the java.lang.Class class, you have use that the find the methods.
Given a method name and the parameter types you can find a particular method and get a java.lang.reflect.Method object which represents the method.
Then you can call invoke() on the Method object and pass it the instance of the class you want to call the method on. You have to pass the parameters that match this method as well.
Hope this gets you started.
Ilja Preuss

Joined: Jul 11, 2001
Posts: 14112
Using reflection is rather complicated. For most problems it is more appropriate to introduce an interface containing the function and having the objects implement that interface.
So instead of passing around function pointers, you pass around function objects. Take a look at Runnable for an example.

The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
I agree. Here's the link:
subject: Function Pointer
It's not a secret anymore!