File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Pointer to a Method Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Pointer to a Method" Watch "Pointer to a Method" New topic

Pointer to a Method

Terry Tucker

Joined: Jan 21, 2013
Posts: 24


One of the neat time saving code tricks I used to do in C was to store the address of a function in a pointer for later use. It was slick to be able to decide which function needed to be used somewhere else and then have a block that simply dereferenced the pointer and called the correct function.

During my short stint in the world I Java I have already seen a couple occasions where that functionality would be nice to have. Can one do this kind of thing in Java? I have experimented with this but to no avail. Just wondering if any of the experts here know of a way.


Terry Lee Tucker
Oracle Certified Associate
Jeff Verdegan

Joined: Jan 03, 2004
Posts: 6109

That feature is not available as such. However, there's the java.lang.reflect.Method object, but you shouldn't use reflection unless you have no choice. A better way is to use an interface. The Command Pattern is a reasonable approximation to what you're talking about, at least for some use cases.
Terry Tucker

Joined: Jan 21, 2013
Posts: 24

Thanks for the reply. I will look into Pattern as you suggest.
I agree. Here's the link:
subject: Pointer to a Method
It's not a secret anymore!